2013-06-26 177 views
0

我想知道是否在某些情况下,通过直接比较字符来比较字符串会更少处理器密集型,而不是使用strcmp。使用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更优雅,但对于性能方面的原因,只是直接比较的字符会是更快?

+3

我相信'strcmp()'为'strlen()'等优化你不用担心这一点。 –

+2

如果标准库为您提供诸如字符串比较之类的功能,则应始终偏好这些。 –

+2

我相信你花时间写这个问题的时间要比采用这两个选项中最好的选项所获得的性能增益重要得多。 –

回答

2

直接比较字符是非常邪恶和脆弱的代码。根据编译器和体系结构的不同,优化也可能更难。

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

只是检查字符串是至少足够长的时间(或长度完全正确,但无论如何不能太短)和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()一些实现,甚至会比焦炭焦炭比较快。