I was doing a quick performance test on a block of code
void ConvertToFloat( const std::vector< short >& audioBlock,
std::vec
Does resize initialize the newly allocated vector where reserve just allocates but does not construct?
Yes.
out.resize( audioBlock.size() );
Since out
's size (= 0) is lesser than audioBlock.size()
, additional elements are created and appended to the end of the out
. This creates the new elements by calling their default constructor.
Reserve only allocates the memory.
Resize()
Modifies the container so that it has exactly n elements, inserting elements at the end or erasing elements from the end if necessary. If any elements are inserted, they are copies of t. If n > a.size()
, this expression is equivalent to a.insert(a.end(), n - size(), t)
. If n < a.size()
, it is equivalent to a.erase(a.begin() + n, a.end())
.
Reserve()
If n is less than or equal to capacity()
, this call has no effect. Otherwise, it is a request for allocation of additional memory. If the request is successful, then capacity()
is greater than or equal to n; otherwise, capacity()
is unchanged. In either case, size()
is unchanged.
Memory will be reallocated automatically if more than capacity() - size()
elements are inserted into the vector. Reallocation does not change size()
, nor does it change the values of any elements of the vector. It does, however, increase capacity()
Reserve causes a reallocation manually. The main reason for using reserve()
is efficiency: if you know the capacity to which your vector must eventually grow, then it is usually more efficient to allocate that memory all at once rather than relying on the automatic reallocation scheme.
First code writes to out[i]
which boils down to begin() + i
(ie. an addition). Second code uses push_back
, which probably writes immediately to a known pointer equivalent to end()
(ie. no addition). You could probably make the first run as fast as the second by using iterators rather than integer indexing.
Edit: also to clarify some other comments: the vector contains floats, and constructing a float is effectively a no-op (the same way declaring "float f;" does not emit code, only tells the compiler to save room for a float on the stack). So I think that any performance difference between resize()
and reserve()
for a vector of floats is not to do with construction.