Is there a difference in runtime if a heavy calculations is in the conditional part of the loop?
For example:
int i,n;
for(i=1;i<=[call to some complex function on n];i++)
...
Or
int i,n,foo;
foo=[call to some complex function on n];
for(i=1;i<=foo;i++)
...
Which one is more efficient? does the loop make the calculation once or with each iteration?
Yes, there will be a "performance hit" for functions provided in the conditional part of a for
loop unless the function is const and the compiler can reduce it down to a constant value. The compiler will need to call the function for each iteration.
I highly recommend placing the result of the function into a constant temporary variable before entering the loop.
Example:
const unsigned int limit = my_vector.size();
for (unsigned int i = 0; i < limit; ++i)
{
// iterate over vector
}
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