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


is there difference in runtime if heavy calculations in conditional part of loop?

for example:

int i,n; for(i=1;i<=[call complex function on n];i++) ... 

or

int i,n,foo; foo=[call complex function on n]; for(i=1;i<=foo;i++) ... 

which 1 more efficient? loop make calculation once or each iteration?

yes, there "performance hit" functions provided in conditional part of for loop unless function const , compiler can reduce down constant value. compiler need call function each iteration.

i highly recommend placing result of function constant temporary variable before entering loop.

example:

const unsigned int limit = my_vector.size(); (unsigned int = 0; < limit; ++i) {   // iterate on vector } 

Comments

Popular posts from this blog

javascript - ScrollTo Effect (href to div) -

javascript - ng-class not responding to change in model in Angular? -

javascript - document.registerElement extending HTMLInputElement prototype while using custom tag name to avoid implicit browser style -