我想要另一个条件 - 仍然保持快速执行时间但更安全 - 如果其中一个或两个字符串为空,我返回false:

int speicial_strcmp(char *str1, char* str2 )
{

    if(*str1==*str2 =='\0')
         return 0;

     return strcmp(str1,str2);

}
有帮助吗?

解决方案

不,这不是一个好方法,因为它不起作用。

if(*str1==*str2 =='\0')

将被评估为:

bool tmp1 = *str1==*str2;
bool tmp2 = tmp1 == '\0';
if (tmp2)

换句话说,因为bool会被提升为一个整数,只要字符串以不同的字符开头,你的测试就会返回true( tmp1 将为false,转换为0,等等 tmp2 变为true)

不要试图超越编译器。编写快速代码不是为了编写尽可能少的代码行,甚至是尽可能短的代码行。即使以这种方式将 == 链接在一起是有意义的,也没有理由为什么它会更快。只需编写您理解的代码,并且可以正确编写。

其他提示

即使你实施了正确建议的早期测试,你也不太可能通过做这类事情来加快速度 - 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;
}

它已经尽可能快地有意义了。你的无关检查只会使你不感兴趣的案件更慢。

if( *str1 == 0 || *str2 == 0 )
   return 0;

您提供的示例甚至无法正常运行。 strcmp()将停在第一个不同的字符处。如果两个字符串都是空的,则由您的“特殊情况”满足。在上面,这将像您给出的示例一样快速地处理。

通过为这两个字符串添加一个特殊的处理程序,如上所述,你只是将它们不存在的情况,相应地更慢。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top