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\'00
When comparing performance, I've found that it's best to put the test functions and the test driver in separate compilation units. Put your test functions in separate compilation units, and compile those to whatever optimization level you want, but compile the test driver unoptimized. Otherwise you will run into exactly the kind of problem you've seen here.
The problem is that strcmp
compares two const
C-style strings. If you loop 500,000,000 times over strcmp(string_a, string_b)
, an optimizing compiler is going to be smart enough to reduce that loop to optimize that loop away, and then perhaps smart enough to optimize away the one remaining call to strcmp
.
Your compare function takes two non-const strings. As far as the compiler is concerned, your function may well have side effects. The compiler doesn't know, so it can't optimize the loop down to nothing. It has to generate code to perform the comparison 500,000,000 times.