Re: String comparison for fixed strings

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Leslie P. Polzer wrote:

> > 3. An actual loop is typically quicker than an "unrolled" loop (where
> > you just repeat the loop body) as it results in smaller code and thus
> > better cache coherency.
> 
> I'm not sure whether it was the OP's intention to talk about
> the (dis)advantages of unrolled code.

No, but Stephen mentioned that strcmp() "uses a do/while loop".
On a modern CPU, branches don't normally take any CPU cycles.

> > All things considered, strcmp() is likely to be faster.
> 
> Given these things:
> 
> 1. The null byte check is mandatory.
> 
> 2. The haystack string is not _considerably_ larger than the
>    needle string.

Huh? The question was about strcmp(), not strstr().

For strcmp(), you don't really gain much by having the string fixed. 
If you are performing the check often enough, the string will be
cached. If the check is infrequent, a single strcmp() function is more
likely to be cached than several fixed-string checks. The strings
themselves won't necessarily be cached, but a cache miss for data is a
lot less significant than a cache miss for code.

For strstr() with a fixed "needle", a pre-compiled finite automaton
will win. With a variable "needle", if the "haystack" is large enough,
even a dynamically-generated finite automaton will be faster than an
strncmp() loop.

-- 
Glynn Clements <glynn@xxxxxxxxxxxxxxxxxx>
-
To unsubscribe from this list: send the line "unsubscribe linux-c-programming" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at  http://vger.kernel.org/majordomo-info.html

[Index of Archives]     [Linux Assembler]     [Git]     [Kernel List]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [C Programming]     [Yosemite Campsites]     [Yosemite News]     [GCC Help]

  Powered by Linux