Reputation: 1987
I am not sure how fast the below code is. If anyone knows the faster/optimized code than this, please let me know.
int xstrcmp(char *s1, char *s2)
{
while (*s1 == *s2++)
if (*s1++ == 0)
return (0);
return (*(const unsigned char *)s1 - *(const unsigned char *)(s2-1));
}
Upvotes: 10
Views: 26675
Reputation: 40669
If I'm testing for equality, sometimes I write this:
if (a[0]==b[0] && strcmp(a, b)==0){.....
so it will only call strcmp
if the first characters match, which most of the time they don't.
Upvotes: 5
Reputation: 19384
Use ::strcmp
instead of your own hand-rolled version. Your compiler vendor has most likely an assembly-only version which uses CPU-specific features for comparison (SSE4.2 for instance has special instructions for fast string comparison.) The MSVC version is written in assembly for instance and uses larger compares (whole words instead of individual characters) as much as possible, special casing unaligned starts/ends of the string (if you have VS2010 installed, it's in VC/crt/src/intel/strcmp.asm
.)
Upvotes: 18
Reputation: 1756
Have you measured how much faster this is than strcmp? C strcmp should already be well optimized.
Some other methods you could take:
Upvotes: 5