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

后端 未结 6 1037
梦毁少年i
梦毁少年i 2021-02-19 01:20

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

6条回答
  •  时光说笑
    2021-02-19 01:55

    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.

提交回复
热议问题