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

后端 未结 7 1096
孤城傲影
孤城傲影 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:51

    In every implementation I've, seen vector::size() performs a subtraction of end() and begin(), ie its not as fast as reading a variable.

    When implementing a vector, the implementer has to make a choice between which shall be fastest, end() or size(), ie storing the number of initialized elements or the pointer/iterator to the element after the last initialized element. In other words; iterate by using iterators.

    If you are worried of the size() performance, write your index based for loop like this;

    for (size_t i = 0, i_end = container.size(); i < i_end; ++i){
    // do something performance critical
    }
    

提交回复
热议问题