I wrote a function, Str::Compare
, that is basically a strcmp
rewritten in another way.
While comparing the two function, in a loop repeted 500'000'000 times, strcmp
execute too much fast, about x750 times faster.
This code was compiled in a C library with -Os
parameter active:
int Str::Compare(char* String_1, char* String_2)
{
char TempChar_1, TempChar_2;
do
{
TempChar_1 = *String_1++;
TempChar_2 = *String_2++;
} while(TempChar_1 && TempChar_1 == TempChar_2);
return TempChar_1 - TempChar_2;
}
The execution time of that function is 3.058s
, while strcmp
only 0.004s
.
Why this happen?
Also this is how I implemented the benchmark loop:
int main()
{
char Xx[] = {"huehuehuehuehuehuehuehuehuehuehuehuehuehue"},
Yy[] = {"huehuehuehuehuehuehuehuehuehuehuehuehuehue"};
for(int i = 0; i < 500000000; ++i)
Str::Compare(Xx, Yy);
}
Edit:
While testing some code I wrote and optimization that improved drastically Str::Compare
speed.
If before strcmp
was x750 times faster now is only x250. This is the new code:
int Str::Compare(char* String_1, char* String_2)
{
char TempChar_1, TempChar_2, TempChar_3;
while(TempChar_1 && !TempChar_3)
{
TempChar_1 = *String_1++;
TempChar_2 = *String_2++;
TempChar_3 = TempChar_1 ^ TempChar_2;
}
return TempChar_1 - TempChar_2;
}
New execution time is 0.994s
.
while(*str1++ == *str2++);
– Edelman1
the edited version ofStr::Compare
is not good -TempChar_3
is used before being initialized,2
Code generated by VS2010 for original function is almost as fast asstrcmp
.3
it's hard to beat massively optimized function (even intrinsic!) with a straightforward implementation. – Broncowhile(*str_1 && *str_1++ == *str_2++);
Actually is the correct form. That is more slow for the simple reason that the processor must resolve the address of the pointer every time, with a performace-loss. – Ziagos