Search code examples
cstringstrcmp

Is checking for first character before doing strcmp useful?


which of the following is more efficient :

if (strcmp(str1,str2) != 0) {
...
}

OR

if (str1[0]!=str2[0] && strcmp(str1,str2) !=0 ) {
...
}

If str2 is always unique and there can be multiple str1.


Solution

  • There is no need of second version as strcmp is usually implemented very smartly to compare multiple characters at once.

    In second version, because of short-circuit property of &&, you may save a function call. You should benchmark both version for your requirements to get the correct idea.

    But my suggestion still is, there is no need of version 2 (str1[0]!=str2[0] && strcmp(str1,str2) !=0 ) proposed by you unless strcmp is proved as bottleneck (in profiling result) for your requirement and there are evidences that version 2 performs better.