c++for-loopcompiler-optimizationloop-invariant

For loop, is it faster to check the size of a vector outside the loop?


My question is regarding time optimisation. Is the for loop faster by doing:

std::vector<int> myVec = {0,1,2,3};
for(int i = 0; i < myVec.size(); i++){}

Or is it best practice to compute the size beforehand?

std::vector<int> myVec = {0,1,2,3};
int myVecSize = myVec.size();
for(int i = 0; i < myVecSize ; i++){}

I'm wondering here not only about pure time execution, but also if it could lead to some problems to do in a way or another


Solution

  • It is not important at all. Optimizing compiler will remove those two or three lines, they do nothing.

    Seriously. If compiler could deduce if a container is not changed in a loop, it would do optimization that you did manually. To help compiler to apply optimization you can even declare a container be constant (example for vector):

    const std::vector<int> myVec = {0,1,2,3};