【问题标题】:Using strcmp to compare strings vs. comparing characters directly使用 strcmp 比较字符串与直接比较字符
【发布时间】:2013-06-26 14:15:19
【问题描述】:

我想知道在某些情况下,与使用 strcmp 相比,通过直接比较字符来比较字符串会不会占用更少的处理器。

对于一些背景信息,我在一个处理能力不强的嵌入式系统中使用 C 进行编码。它必须读取传入的字符串并根据传入的字符串执行某些任务。

假设传入的字符串是"BANANASingorethispartAPPLESignorethisalsoORANGES"。我想验证BANANASAPPLESORANGES 是否存在于它们的确切位置。我的代码会这样做:

input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
char compare[100];            //array to hold input to be compared
strncopy(compare,input,7);    //copy "BANANAS" to compare
compare[7] = "\0";            //terminate "BANANAS"
if (strcmp(compare, "BANANAS") == 0){
    strncopy(compare,input[21],6); //copy "APPLES" to compare
    compare[6] = "\0";             //terminate "APPLES"
    if(strcmp(compare,"APPLES")==0){
        //repeat for "ORANGES"
    }
}

或者,我可以直接比较字符:

input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
if(input[0]=='B' && input[1]=='A' && input[2]=='N' && input[3]=='A' && input[4]=='N' && input[5]=='A' && input[6]=='S'){
    if(input[21]=='A' && input[22]=="P"  <snipped> ){
        if(input[30]=='O' <snipped> ){
            //input string matches my condition!
        }
    }
}   

使用 strncopy+strcmp 更优雅,但出于性能考虑,直接比较字符会更快吗?

【问题讨论】:

  • 我相信strcmp()strlen() 等是最适合你的,不用担心。
  • 如果标准库为您提供了诸如字符串比较之类的功能,那么您应该总是更喜欢那些。
  • 我相信你花在写这个问题上的时间远比采用这两个选项中的最佳选项所获得的性能提升重要得多。
  • 使用 strncopy 复制输入的一部分所需的时间是否微不足道?直接字符比较不需要复制。
  • 请注意,您可以通过进行 32/64 位 int 比较来做一些更聪明的事情:*(uint32_t *)input == *(uint32_t *)"BANA" 一次检查 4 个字符。大多数 strcmp 都会做这样的聪明事

标签: c performance strcmp


【解决方案1】:

直接比较字符是非常卑鄙和脆弱的代码。取决于编译器和架构,它也可能更难优化。

另一方面,你的副本是一种浪费——它没有任何用处。

只需检查字符串是否至少足够长(或完全正确,但不要太短)并且strncmp(或memcmp)到位。

#define COMPARE(IN, OFF, SUB) memcmp(IN+OFF, SUB, sizeof(SUB)-1)

input = "BANANASingorethispartAPPLESignorethisalsoORANGES";

if (COMPARE(input,  0, "BANANAS") == 0 &&
    COMPARE(input, 21, "APPLES" ) == 0 &&
    COMPARE(input, 40, "ORANGES") == 0) )
{

【讨论】:

    【解决方案2】:

    在您的情况下,您最好使用memcmp() 以避免复制数据:

    input = "BANANASingorethispartAPPLESignorethisalsoORANGES";
    if (memcmp(input, "BANANAS",    7) == 0  &&
        memcmp(input+21, "APPLES",  6 ) == 0 &&
        memcmp(input+40, "ORANGES", 8 ) == 0   )
    {
        // everything matches ...
    }
    

    至少memcmp() 的某些实现甚至会比逐个字符比较更快。

    【讨论】:

      猜你喜欢
      • 2011-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 2019-06-19
      • 1970-01-01
      相关资源
      最近更新 更多