std::vector::size
has constant time complexity, so yes, it is already stored in the vector and the code is redundant.
Is it faster to cache the size of std::vector
-
05-03-2022 - |
题
I'm looking at a C++ class that wraps around std::vector and stores the size of the vector. The class updates this size everytime the vector is modified leading to a lot of redundant code (as an up-to-date size is always available from the size() method). Is this truly faster or would the compiler optimize iterated usage of size() anyway?
解决方案 2
其他提示
First, unlike what is stated in the previous postings, the
implementations of std::vector
that I've seen (MS and g++) do
not cache the size. On the other hand, it can be calculated
by a simple pointer subtraction, and anything you do to cache
the size will almost certainly add more overhead than it saves.
On all implementations I've seen, caching would be slower. It's just wasting memory bandwidth.
As far as I know, the standard library implementation of vector::size
is just returning a cached size, not recalculating it each time.