Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best or fastest way to compare two strings?

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));
}
like image 479
Jatin Avatar asked Feb 25 '12 08:02

Jatin


2 Answers

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.

like image 66
Mike Dunlavey Avatar answered Sep 27 '22 23:09

Mike Dunlavey


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.)

like image 30
Anteru Avatar answered Sep 27 '22 22:09

Anteru