Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it expensive to compute vector size in for loops, each iteration?

Tags:

c++

c++11

Does the c++ compiler take care of cases like, buildings is vector:

for (int i = 0; i < buildings.size(); i++) {}

that is, does it notice if buildings is modified in the loop or not, and then based on that not evaluate it each iteration? Or maybe I should do this myself, not that pretty but:

int n = buildings.size();
for (int i = 0; i < n; i++) {}
like image 343
user2381422 Avatar asked Jun 05 '13 16:06

user2381422


3 Answers

buildings.size() will likely be inlined by the compiler to directly access the private size field on the vector<T> class. So you shouldn't separate the call to size. This kind of micro-optimization is something you don't want to worry about anyway (unless you're in some really tight loop identified as a bottleneck by profiling).

like image 106
Timothy Shields Avatar answered Nov 16 '22 15:11

Timothy Shields


Don't decide whether to go for one or the other by thinking in terms of performance; your compiler may or may not inline the call - and std::vector::size() has constant complexity, too.

What you should really consider is correctness, because the two versions will behave very differently if you add or remove elements while iterating.

If you don't modify the vector in any way in the loop, stick with the former version to avoid a little bit of state (the n variable).

like image 28
Frerich Raabe Avatar answered Nov 16 '22 13:11

Frerich Raabe


If the compiler can determine that buildings isn't mutated within the loop (for example if it's a simple loop with no function calls that could have side effects) it will probably optmize the computation away. But computing the size of a vector is a single subtraction anyway which should be pretty cheap as well.

Write the code in the obvious way (size inside the loop) and only if profiling shows you that it's too slow should you consider an alternative mechanism.

like image 2
Mark B Avatar answered Nov 16 '22 15:11

Mark B