I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
I'm not sure if the following code can cause redundant calculations, or is it compiler-specific?
for (int i = 0; i < strlen(ss); ++i)
{
// blabla
}
Will strlen()
be calculated every time when i
increases?
The predicate code in it's entirety will be executed on every iteration of the
for
loop. In order to memoize the result of thestrlen(ss)
call the compiler would need to know that at leaststrlen
was side effect freess
doesn't change for the duration of the loopThe compiler doesn't know either of these things and hence can't safely memoize the result of the first call
Yes. The test doesn't know that ss doesn't get changed inside the loop. If you know that it won't change then I would write:
Yes, every time you use the loop. Then it will every time calculate the length of the string. so use it like this:
In the above code
str[i]
only verifies one particular character in the string at locationi
each time the loop starts a cycle, thus it will take less memory and is more efficient.See this Link for more information.
In the code below every time the loop runs
strlen
will count the length of the whole string which is less efficient, takes more time and takes more memory.A good compiler may not calculate it every time, but I don't think you can be sure, that every compiler does it.
In addition to that, the compiler has to know, that
strlen(ss)
does not change. This is only true ifss
is not changed infor
loop.For example, if you use a read-only function on
ss
infor
loop but don't declare thess
-parameter asconst
, the compiler cannot even know thatss
is not changed in the loop and has to calculatestrlen(ss)
in every iteration.Formally yes,
strlen()
is expected to be called for every iteration.Anyway I do not want to negate the possibility of the existance of some clever compiler optimisation, that will optimise away any successive call to strlen() after the first one.
Yes.
strlen()
calculated everytime wheni
increases and does not optimized.Below code shows why the compiler should not optimize
strlen()
.