Just use the standard C strcmp()
or C++ std::string::operator==()
for your string comparisons.
The implementations of them are reasonably good and are probably compiled to a very highly optimized assembly that even talented assembly programmers would find challenging to match.
For example, GNU GLIBC's implementation of strcmp():
int
strcmp (p1, p2)
const char *p1;
const char *p2;
{
register const unsigned char *s1 = (const unsigned char *) p1;
register const unsigned char *s2 = (const unsigned char *) p2;
unsigned reg_char c1, c2;
do
{
c1 = (unsigned char) *s1++;
c2 = (unsigned char) *s2++;
if (c1 == '\0')
return c1 - c2;
}
while (c1 == c2);
return c1 - c2;
}
... Compiled with GCC 4, with -O2 optimization on x86_64:
0000000000000000 <strlen>:
0: 66 0f ef d2 pxor %xmm2,%xmm2
4: 48 89 f9 mov %rdi,%rcx
7: 49 89 f8 mov %rdi,%r8
a: 48 83 e7 f0 and $0xfffffffffffffff0,%rdi
e: 66 0f 6f ca movdqa %xmm2,%xmm1
12: 66 0f 74 17 pcmpeqb (%rdi),%xmm2
16: 83 ce ff or $0xffffffffffffffff,%esi
19: 48 29 f9 sub %rdi,%rcx
1c: d3 e6 shl %cl,%esi
1e: 66 0f d7 d2 pmovmskb %xmm2,%edx
22: 21 f2 and %esi,%edx
24: 75 15 jne 3b <strlen+0x3b>
26: 66 0f 6f 47 10 movdqa 0x10(%rdi),%xmm0
2b: 48 8d 7f 10 lea 0x10(%rdi),%rdi
2f: 66 0f 74 c1 pcmpeqb %xmm1,%xmm0
33: 66 0f d7 d0 pmovmskb %xmm0,%edx
37: 85 d2 test %edx,%edx
39: 74 eb je 26 <strlen+0x26>
3b: 4c 29 c7 sub %r8,%rdi
3e: 0f bc c2 bsf %edx,%eax
41: 48 01 f8 add %rdi,%rax
44: c3 retq
... Which reads each string 16 bytes at a time (movdqa
) on an aligned boundary (line a
), comparing (pcmpeqb
), and stopping at any inequality or the NUL byte (33
-39
); which is about the most efficient this operation can be.
So don't sweat the small stuff. I'd suggest looking at optimizing other parts of your code.