Home >Backend Development >C++ >Is `std::vector` Really Slower Than Native Arrays?
Is std::vector Significantly Slower Than Native Arrays?
You might have heard it said that std::vector is essentially implemented as an array, implying that their performance should be comparable. However, your recent testing suggests otherwise, with std::vector exhibiting a significant performance penalty. This article aims to clarify whether std::vector is indeed much slower than native arrays.
Performance Analysis
The provided test code measures the time taken to initialize a large array of Pixel objects using three different methods: std::vector with resize(), std::vector with push_back(), and a plain array allocated with malloc(). The results indicate that std::vector with resize() is about 4 times slower than a plain array, while std::vector with push_back() is even slower.
However, upon closer examination, it becomes apparent that the performance difference stems from the fact that the test code iterates over the vector twice. The first iteration initializes the objects, and the second iteration simply reads them. This is done to facilitate a fair comparison with the plain array, which can only be initialized once.
Revised Test
To accurately compare the performance of std::vector to native arrays, the test code was modified to initialize the vector only once:
std::vector<Pixel> pixels(dimensions * dimensions, Pixel(255, 0, 0));
With this modification, the performance gap between std::vector and a plain array became negligible:
g++ -O3 Time.cpp -I <MyBoost> ./a.out UseVector completed in 2.216 seconds
Conclusion
Based on the revised test results, the performance of std::vector is comparable to that of native arrays. The apparent slowness observed in the initial tests was due to the inefficient initialization method used for std::vector. When initialized properly, std::vector exhibits minimal performance overhead compared to native arrays.
It should be noted that the test results presented are specific to the Pixel class and the particular initialization patterns employed. Performance may vary for other classes and initialization scenarios.
The above is the detailed content of Is `std::vector` Really Slower Than Native Arrays?. For more information, please follow other related articles on the PHP Chinese website!