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

后端 未结 6 820
梦毁少年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:05

    Only start to manually optimize stuff like that, if it's really a performance problem. Then measure the difference. Otherwise you'll lot's of unmaintainable ugly code that's harder to debug and less productive to work with. Most leading compilers will probably optimize it away, if the size doesn't change within the loop.

    But even if it's not optimized away, then it will probably be inlined (since templates are inlined by default) and cost almost nothing.

提交回复
热议问题