I have frequently noticed the following pattern:
for (int i = 0; i < strlen(str); ++i) {
// do some operations on string
}
The complexity of above loop would be O(N²) because the complexity of strlen is N and that comparison is made during every iteration.
However, if we calculate strlen before the loop and use that constant, the complexity of the loop is reduced to O(N).
I am sure there are many other such optimizations.
Does the compiler carry out such optimizations or do programmers have to take precautions to prevent it?
While I don't have any solid evidence whatsoever, my guess would be this:
The compiler makes a data flow analysis of the variable str. If it's potentially modified inside the loop or marked as volatile, there is no guarantee that strlen(str) will remain constant between iterations and therefore cannot be cached. Otherwise, it should be safe to cache and would be optimized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With