Question

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?

Était-ce utile?

La solution 2

std::vector::size has constant time complexity, so yes, it is already stored in the vector and the code is redundant.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top