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));
}
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.
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
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With