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

后端 未结 6 806
梦毁少年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 02:04

    Assuming the size() function is an inline function for the base-template, one can also assume that it's very little overhead. It is far different from, say, strlen() in C, which can have major overhead.

    It is possible that it's still faster to use int n = buildings.size(); - because the compiler can see that n is not changing inside the loop, so load it into a register and not indirectly fetch the vector size. But it's very marginal, and only really tight, highly optimized loops would need this treatment (and only after analyzing and finding that it's a benefit), since it's not ALWAYS that things work as well as you expect in that sort of regard.

提交回复
热议问题