dan gha
dan gha

Reputation: 79

C++ 2D vector initialization time

Why does 2D vector initialization take 20 times longer than 1D?

this takes 32ms :

vector<vector<float>>a(1000000,vector<float>(1));

but this one takes 1.3ms :

vector<float> b(1000000);

and its worse without optimization.

Upvotes: 0

Views: 209

Answers (1)

Dzemo997
Dzemo997

Reputation: 336

If you look at vector implementation you'll notice that a new operator is used to allocating memory for each element. Using dynamic allocation for 2D array (vector) you need to allocate memory for each row (call new operator n times, where n is the number of the vectors first dimension). Operator new is not very fast because it calls malloc function to allocate memory on the heap. Constructor for 2D vector is implemented something like this:

 vector = new T*[n];
  for(size_t i = 0; i < n; ++i){
    vec[i] = new T[m];
  }

Where T is a generic type, n is the first dimension, m is the second dimension.

Upvotes: 3

Related Questions