Performance of vector::size() : is it as fast as reading a variable?

后端 未结 7 1228
孤城傲影
孤城傲影 2020-12-30 20:38

I have do an extensive calculation on a big vector of integers. The vector size is not changed during the calculation. The size of the vector is frequently accessed by the c

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-30 21:01

    I always save vector.size() in a local variable (if the the size doesn't change inside the loop!).
    Calling it on each iteration vs. saving it in a local variable can be faster. At least, that's what I experienced.
    I can't give you any real numbers, as I tested this a very long time ago. However from what I can recall, it made a noticeable difference (however potentially only in debug mode), especially when nesting loops.

    And to all the people complaining about micro-optimization:
    It's a single additional line of code that introduces no downsides.

提交回复
热议问题