2013-06-26 52 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()一些實現,甚至會比焦炭焦炭比較快。