Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

The cost of incrementally growing a vector vs. having a pre-grown vector

15 views
Skip to first unread message

Bonita Montero

unread,
Apr 20, 2023, 12:47:31 AM4/20/23
to
I was interested what's the cost of incrementally growing a vector<>
vs. having a pre-grown vector that only has []-assingments:

#include <iostream>
#include <vector>
#include <chrono>

using namespace std;
using namespace chrono;

int main()
{
vector<char> vc( 1u << 30 ); // prevent dyanmic commit
vc.resize( 0 );
auto timed = [&]<typename Fn>( char const *header, Fn fn )
{
auto start = high_resolution_clock::now();
size_t n = vc.capacity();
for( size_t i = 0; i != n; ++i )
fn( i );
double s = duration_cast<nanoseconds>( high_resolution_clock::now() -
start ).count() / 1.0e9;
cout << header << s << endl;
};
timed( "incremental: ", [&]( size_t i ) { vc.emplace_back( (char)i ); } );
timed( "immediate: ", [&]( size_t i ) { vc[i] = (char)i; } );
}

On my Windows-PC with MSVC (AMD 3990X) having a pre-grown vector is
about +11% faster. On my Linux-PC (G4400) both timings are faster
and having a pre-grown vector is +173% faster. I didn't expect such
results.

Paavo Helde

unread,
Apr 20, 2023, 5:04:11 AM4/20/23
to
You are leaving the vector building ("pre-growing") step out of the
"immediate" timing. Of course it is faster.


Bonita Montero

unread,
Apr 20, 2023, 5:39:32 AM4/20/23
to
No, the vector has still its old size. The thing that I wanted to
benchmark is the difference of between a vector which grows to its
own capacity (first timing) vs. a pre-grown vector (second timing).
On Linux the performance-difference is significant.

0 new messages