Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector initializing slower than array...why?

I tried 2 things: (pseudo code below)

int arr[10000];
for (int i = 0; i < 10000; i++)
{
   for (int j = 0; j < 10000; j++)
   {
       arr[j] = j;
   }
}

and

vector<int> arr(10000);
for (int i = 0; i < 10000; i++)
{
   for (int j = 0; j < 10000; j++)
   {
       arr[j] = j;
   }
}

I ran both the programs and timed it using the "time" shell command. Program 1 runs in 5 seconds, program 2 runs in 30 seconds. I ran both programs with compiler optimization turned on, and both programs ran in about the same time (0.38s). I am confused by these results. Can someone please explain to me why this is happening?

Thanks!

like image 203
Aishwar Avatar asked Oct 23 '09 17:10

Aishwar


3 Answers

For the template, subscripting is done with operator[]. With optimization turned off, that'll usually be generated as a real function call, adding a lot of overhead to something as simple as subscripting into an array. When you turn on optimization, it's generated inline, removing that overhead.

like image 155
Jerry Coffin Avatar answered Nov 18 '22 22:11

Jerry Coffin


In debugging mode, implementations of std::vector provide a lot of run-time checking for ease of use. This checking is not available for native arrays. For example, in VC2008, if you compile your vector example in debugging mode, there will be range-checking even in the case of operator[].

like image 33
Khaled Alshaya Avatar answered Nov 18 '22 22:11

Khaled Alshaya


If your non-optimized vector implementation is performing bounds checking, that would account for the discrepancy.

like image 5
Dan Blanchard Avatar answered Nov 18 '22 22:11

Dan Blanchard