Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::vector reserve() and push_back() is faster than resize() and array index, why?

I was doing a quick performance test on a block of code

void ConvertToFloat( const std::vector< short >& audioBlock,                       std::vector< float >& out ) {     const float rcpShortMax = 1.0f / (float)SHRT_MAX;     out.resize( audioBlock.size() );     for( size_t i = 0; i < audioBlock.size(); i++ )     {         out[i]  = (float)audioBlock[i] * rcpShortMax;     } } 

I was happy with the speed up over the original very naive implementation it takes just over 1 msec to process 65536 audio samples.

However just for fun I tried the following

void ConvertToFloat( const std::vector< short >& audioBlock,                       std::vector< float >& out ) {     const float rcpShortMax = 1.0f / (float)SHRT_MAX;     out.reserve( audioBlock.size() );     for( size_t i = 0; i < audioBlock.size(); i++ )     {         out.push_back( (float)audioBlock[i] * rcpShortMax );     } } 

Now I fully expected this to give exactly the same performance as the original code. However suddenly the loop is now taking 900usec (i.e. it's 100usec faster than the other implementation).

Can anyone explain why this would give better performance? Does resize() initialize the newly allocated vector where reserve just allocates but does not construct? This is the only thing I can think of.

PS this was tested on a single core 2Ghz AMD Turion 64 ML-37.

like image 256
Goz Avatar asked Sep 22 '09 16:09

Goz


People also ask

Is std::vector faster than array?

A std::vector can never be faster than an array, as it has (a pointer to the first element of) an array as one of its data members. But the difference in run-time speed is slim and absent in any non-trivial program. One reason for this myth to persist, are examples that compare raw arrays with mis-used std::vectors.

Which is faster vector or array C++?

The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.

Is vector Push_back slow?

The main reason why push_back is slow is because of multiple reallocation of memory. Every vector has vector::size and vector::capacity. vector::size gives the number of elements in the vector and vector::capacity gives the number of elements vector can store.

What is the time complexity of Push_back?

push_back(): Inserts a new element at the end of the vector. Its time complexity is O(1).


1 Answers

Does resize initialize the newly allocated vector where reserve just allocates but does not construct?

Yes.

like image 84
sepp2k Avatar answered Oct 04 '22 14:10

sepp2k