Say I had code that looked like this:
string foo = "bar";
for(int i = 0; i < foo.length(); i++){
//some code that does not modify the length of foo
}
Would the GNU compiler be smart enough to realize that the length of foo
does not change over the course of this loop and replace the foo.length()
call with the proper value? Or would foo.length()
be called for every i
comparison?
The only way to know for sure is to try it and take a look at the assembly.
My guess is that if the call to length()
is inlined, then Loop Invariant Code Motion will hoist the internals of length()
out of the loop and replace it with a single variable.
As a second thought, this might even be moot. The size of a string is probably just a simple field in the string
class - which is on the stack. So just inlining the call to length()
will already have the effect of reducing the call to a simple variable access.
EDIT :
In this latter case, it doesn't even matter whether or not the length of foo
is modified inside the loop. Getting the length of a string is already just a variable access.