The result of a discussion with a colleague I ended up writing benchmarks to test std::vector
vs raw dynamically allocated arrays, and ended up with a surprise.
My tests are as follows:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * const intArray = new int[ numInts ];
++intVector[0]; // force access to affect optimization
++intArray[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intArray[i];
}
delete[] intArray;
return 0;
}
and:
#include "testconsts.h" // defines NUM_INTS across all tests
#include <vector>
int main()
{
const int numInts = NUM_INTS;
std::vector<int> intVector( numInts );
int * intArray = new int[ numInts ];
++intArray[0]; // force access to affect optimization
++intVector[0]; // force access to affect optimization
for( int i = 0; i < numInts; ++i )
{
++intVector[i];
}
delete[] intArray;
return 0;
}
They are compiled with g++ -O3 with gcc 4.4.3
The results of multiple runs of benchmarking using time
are similar to:
Array:
real 0m0.757s
user 0m0.176s
sys 0m0.588s
Vector:
real 0m0.572s
user 0m0.268s
sys 0m0.304s
Three things are clear:
- Array is faster in user time
- Vector is faster less system time
- Over all vector won this fight
The question is "why?".
The system time issue I'm guessing must have to do with page faults, but I can't describe for myself exactly why one would have significantly more page faults.
As for the user time issue, it's less interesting to me, but I'm still curious of opinions on that as well. I had imagined it had something to do with initialization, though I'm not passing an initialization value to the vector constructor so I don't know.