I was reviewing some code and I saw someone do a
if (0 == strcmp(foo,""))
I am curious because I think it would be faster to do a
if (foo[0] == '\0')
Is this correct or is strcmp optimized enough to make them the same.
(I realize that even if there was some difference it would be small, but am thinking you save at least a few instructions by using my method.)
You're right: since calling strcmp()
adds up the stack management and the memory jump to the actual strcmp instructions, you'll gain a few instructions by just checking the first byte of your string.
For your curiosity, you can check the strcmp() code here: http://sourceware.org/git/?p=glibc.git;a=blob;f=string/strcmp.c;h=bd53c05c6e21130b091bd75c3fc93872dd71fe4b;hb=HEAD
(I thought the code would be filled with #ifdef
and obscure __GNUSOMETHING
, but it's actually rather simple!)