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 - How to synchronize the Three.js and HTML/SVG coordinate systems (especially w.r.t. the y-axis)? -

javascript - How do I find how many occurences are there of a highlighted string, and which occurence is it? -

java - Reading data from multiple zip files and combining them to one -