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!)
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!)
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.
Since C-style strings are always terminated with the null character (\0), you can check whether the string is empty by writing
do {
...
} while (url[0] != '\0');
Alternatively, you could use the strcmp function, which is overkill but might be easier to read:
do {
...
} while (strcmp(url, ""));
Note that strcmp returns a nonzero value if the strings are different and 0 if they're the same, so this loop continues to loop until the string is empty.
Hope this helps!
If you want to check if a string is empty:
if (str[0] == '\0')
{
// your code here
}
No, that's not a good way to do it, because it doesn't work.
if(*str1==*str2 =='\0')
will get evaluated as:
bool tmp1 = *str1==*str2;
bool tmp2 = tmp1 == '\0';
if (tmp2)
In other words, because the bool will get promoted to an integer, your test will return true whenever the strings start with different characters (tmp1 will be false, which gets converted to 0, and so tmp2 becomes true)
Don't try to outsmart the compiler. Writing fast code is not about writing as few lines of code as possible, or even as short lines as possible. Even if chaining together == in this manner was meaningful, there's no reason why it'd be faster. Just write code that you understand, and can write correctly.
Even if you implement the early-out tests you suggest correctly, you are very unlikely to make things any faster by doing this sort of thing - strcmp will already be doing this or nearly this.