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

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top