What is the performance penalty of using std::vector in C++?
c++, c++11, performance, scientific-computing, vector
Solution
Given the abstraction it provides, the C++ `std::vector` is as efficient as it gets: 3 pointers on the stack, and dynamically allocated data that on average does 1 reallocation per element on a linear growth scenario (because the resizing expands the capacity more than proportionally, a factor of 1.5 to 2).
The C equivalent using `malloc()` and `realloc()` would be at least as expensive, and more cumbersome (manual resizing etc.). Moreover, the `std::vector` allows user-defined performance tuning through special allocators (pool-based, stack-allocated, etc.), which in C++11 are not as hard to use as it was in C++98.
If you don't need dynamic resizing, you can code both in C and C++ a static array (or `std::array` in C++).
In general, for high-performance computing, C++ has more potential for optimization, in particular through the use of function objects that can be inlined (in contrast to regular C function pointers). The canonical example is sorting
int comp( const void* a, const void* b ) {
return /* your comparison here */;
}
// C style sorting
qsort( arr, LARGE_SIZE, sizeof( int ), comp );
^^^^ <---- no-inlining through function pointer
// C++11 style sorting (use hand-made function object for C++98
std::sort(std::begin(arr), std::end(arr), [](auto a, auto b) {
return comp(&a, &b);
^^^^ <----- C++11 lambdas can be fully inlined
});
Problem
Typically, I'm interested in knowing if the the standard template library incurs performance/speed overheads in codes for numerical/scientific computing. For eg. Is declaring an array as ``` double 2dmatrix [10][10] ``` going to give me more performance than ``` std::vector<std::vector<double> > 2dmatrix(10,std::vector<double>(10,0.0)) ``` ? I would also appreciate some general ideas, as to whether C has better performance than C++ for scientific computing. I have written my codes in a very Object oriented style using STL , and using C++11 a lot. I am beginning to consider if I should start looking into pure C, if its going to run faster. Any thoughts on this are welcome.