Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a difference in runtime if a heavy calculations function is in the conditional part of the loop?

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?

like image 245
shinzou Avatar asked Mar 17 '23 17:03

shinzou


1 Answers

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
}
like image 122
Thomas Matthews Avatar answered Apr 26 '23 10:04

Thomas Matthews