is this a good way to do a strcmp to return false when strings are empty
I want another condition --still maintain开发者_开发百科ing a fast execution time but safer-- where i return false if either or both strings is empty:
int speicial_strcmp(char *str1, char* str2 )
{
if(*str1==*str2 =='\0')
return 0;
return strcmp(str1,str2);
}
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.
Here's the code for 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;
}
It's already as fast as it could meaningfully be. Your extraneous check only makes the cases you're not interested in, slower.
if( *str1 == 0 || *str2 == 0 )
return 0;
The example you've given won't even run correctly. strcmp()
will stop at the first differing characters. If both strings are empty, as satisfied by your "special case" above, this will be handled just as quickly as the example you've given.
By adding a special handler for both strings empty as above, you've only made the cases where they aren't, correspondingly slower.
精彩评论