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!
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.
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[]
.
If your non-optimized vector implementation is performing bounds checking, that would account for the discrepancy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With