Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strcmp for empty string

Tags:

c

strcmp

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

like image 858
Pablitorun Avatar asked Jun 01 '11 14:06

Pablitorun


2 Answers

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

like image 95
Gui13 Avatar answered Sep 21 '22 19:09

Gui13


strcmp() is a function call and thus has a function call overhead. foo[0] is direct access to the array, so it's obviously faster.

like image 28
ralphtheninja Avatar answered Sep 18 '22 19:09

ralphtheninja