【发布时间】:2013-06-26 14:15:19
【问题描述】:
我想知道在某些情况下,与使用 strcmp 相比,通过直接比较字符来比较字符串会不会占用更少的处理器。
对于一些背景信息,我在一个处理能力不强的嵌入式系统中使用 C 进行编码。它必须读取传入的字符串并根据传入的字符串执行某些任务。
假设传入的字符串是"BANANASingorethispartAPPLESignorethisalsoORANGES"。我想验证BANANAS、APPLES 和ORANGES 是否存在于它们的确切位置。我的代码会这样做:
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