Jatin
Jatin

Reputation: 1987

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));
}

Upvotes: 10

Views: 26675

Answers (3)

Mike Dunlavey
Mike Dunlavey

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

Anteru
Anteru

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

Kevin Hsu
Kevin Hsu

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:

  • Use memcmp if you already know the length of the strings.
  • Compare 4 or 8 chars at a time by reinterpreting strings as int32 or int64 arrays, and handling the remainder chars as chars.
    • You may have issues if your pointers point to non 4-byte or 8-byte aligned memory, so compare as chars until you reach alignment

Upvotes: 5

Related Questions