Does a C++11 range-based for loop condition get evaluated every cycle?
C++PerformanceFor LoopC++11ForeachC++ Problem Overview
for(auto& entity : memoryManager.getItems()) entity->update(mFrameTime);
If memoryManager contains 1000 items, does memoryManager.getItems()
get called 1000 times or only one at the beginning of the loop?
Does the compiler run any optimization with -O2 (or -O3)?
(memoryManager.getItems()
returns a std::vector<Entity*>&
)
C++ Solutions
Solution 1 - C++
It is only evaluated once. The standard defines a range-based for
statement as equivalent to:
{
auto && __range = range-init;
for ( auto __begin = begin-expr, __end = end-expr; __begin != __end; ++__begin ) {
for-range-declaration = *__begin;
statement
}
}
where range-init
is the expression (surrounded by parentheses) or braced-init-list after the :