简体   繁体   English

这是执行strcmp以在字符串为空时返回false的好方法

[英]is this a good way to do a strcmp to return false when strings are empty

I want another condition --still maintaining a fast execution time but safer -- where i return false if either or both strings is empty: 我想要另一个条件-仍然保持快速的执行时间但更安全 -在其中任何一个或两个字符串为空的情况下我返回false:

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) 换句话说,因为布尔值将提升为整数,所以只要字符串以不同的字符开头,您的测试就将返回true( tmp1为false,将转换为0,因此tmp2 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. 只需编写您理解的代码即可正确编写。

即使您正确执行了建议的早期测试,也不太可能通过执行此类操作使速度更快strcmp已经或几乎已经执行了此操作。

Here's the code for strcmp() : 这是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. strcmp()将停在第一个不同的字符处。 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. 通过像上面那样为两个字符串添加一个特殊的处理程序,您仅使它们没有的情况相应地变慢了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM