I am wondering if in certain situations, it would be less processor intensive to compare strings by comparing characters directly, as opposed to using strcmp.
For some background information, I am coding in C in an embedded system with not much processing power. It has to read an incoming string and do certain tasks depending on what the incoming string is.
Say the incoming string is "BANANASingorethispartAPPLESignorethisalsoORANGES"
. I want to verify that BANANAS
, APPLES
, and ORANGES
are present in their exact locations. My code would do this:
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"
}
}
Or, I could compare characters directly:
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!
}
}
}
Using strncopy+strcmp is more elegant, but for performance reasons, would it be faster to just compare characters directly?
Comparing characters directly is pretty vile and fragile code. Depending on the compiler and architecture, it might also be harder to optimize.
On the other hand, your copy is a waste - it does nothing useful.
Just check the string is at least long enough (or exactly the right length, but any way not too short) and strncmp
(or memcmp
) it in place.
#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) )
{