In our C++ course they suggest not to use C++ arrays on new projects anymore. As far as I know Stroustrup himself suggests not to use arrays. But are there significant performance differences?
C++ Performance – Arrays vs std::vectors
arraysc++vector
Related Solutions
Using the following:
g++ -O3 Time.cpp -I <MyBoost>
./a.out
UseArray completed in 2.196 seconds
UseVector completed in 4.412 seconds
UseVectorPushBack completed in 8.017 seconds
The whole thing completed in 14.626 seconds
So array is twice as quick as vector.
But after looking at the code in more detail this is expected; as you run across the vector twice and the array only once. Note: when you resize()
the vector you are not only allocating the memory but also running through the vector and calling the constructor on each member.
Re-Arranging the code slightly so that the vector only initializes each object once:
std::vector<Pixel> pixels(dimensions * dimensions, Pixel(255,0,0));
Now doing the same timing again:
g++ -O3 Time.cpp -I <MyBoost>
./a.out
UseVector completed in 2.216 seconds
The vector now performance only slightly worse than the array. IMO this difference is insignificant and could be caused by a whole bunch of things not associated with the test.
I would also take into account that you are not correctly initializing/Destroying the Pixel object in the UseArrray()
method as neither constructor/destructor is not called (this may not be an issue for this simple class but anything slightly more complex (ie with pointers or members with pointers) will cause problems.
A simpler explanation: you're building with optimisations disabled. You want -O3
, not -o3
.
I don't have clang available to exactly reproduce your tests, but my results are as follows:
//Array run # 1
$ g++ -std=c++11 -O3 test.cpp -o b.out && time ./b.out
real 0m25.323s
user 0m25.162s
sys 0m0.148s
//Vector run #1
$ g++ -std=c++11 -O3 test.cpp -o b.out && time ./b.out
real 0m25.634s
user 0m25.486s
sys 0m0.136s
Best Answer
Using C++ arrays with
new
(that is, using dynamic arrays) should be avoided. There is the problem that you have to keep track of the size, and you need to delete them manually and do all sorts of housekeeping.Using arrays on the stack is also discouraged because you don't have range checking, and passing the array around will lose any information about its size (array to pointer conversion). You should use
std::array
in that case, which wraps a C++ array in a small class and provides asize
function and iterators to iterate over it.Now, std::vector vs. native C++ arrays (taken from the internet):
Note: If you allocate arrays with
new
and allocate non-class objects (like plainint
) or classes without a user defined constructor and you don't want to have your elements initialized initially, usingnew
-allocated arrays can have performance advantages becausestd::vector
initializes all elements to default values (0 for int, for example) on construction (credits to @bernie for reminding me).