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

后端 未结 7 1190
孤城傲影
孤城傲影 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 20:59

    As I understand the 1998 C++ specification, vector::size() takes constant time, not linear time. So, this question likely boils down to whether it's faster to read a local variable than calling a function that does very little work.

    I'd therefore claim that storing your vector's size() in a local variable will speed up your program by a small amount, since you'll only call that function (and therefore the small constant amount of time it takes to execute) once instead of many times.

提交回复
热议问题