Home  >  Article  >  Backend Development  >  Why is std::vector Faster than std::array in Iteration?

Why is std::vector Faster than std::array in Iteration?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 02:51:30144browse

Why is std::vector Faster than std::array in Iteration?

Performance Differential between Iteration through std::array and std::vector

My previous benchmark, which sought to evaluate the iterative performance of std::array and std::vector, contained several imperfections. Upon revisiting the issue, however, I discovered that std::vector is, in fact, faster than std::array.

To alleviate any potential for optimization, I employed several measures, including:

  • Utilizing the loop's result to prevent compiler optimizations
  • Compiling with the -O3 flag for enhanced speed
  • Measuring exclusively the targeted for loop using std::chrono

The resulting execution times for both data structures are as follows:

std::array:

$ g++ arrVsVec.cpp -O3
$ ./a.out
result: 0
time: 99.554109

std::vector:

$ g++ arrVsVec.cpp -O3
$ ./a.out
result: 0
time: 30.734491

Reason for the Discrepancy:

The performance discrepancy stems from the memory pages of the std::array not being resident in the process address space. Specifically, a global scope std::array resides in the .bss section of the executable, which has not been paged in and is initialized to zero. On the other hand, the std::vector has been allocated and initialized to zero, resulting in its memory pages already being present in the address space.

Resolving the Issue:

To eliminate this issue and demonstrate parity between the two data structures, one can add the following code as the first line of main to bring the pages in:

<code class="cpp">std::fill_n(v.data(), n, 1); // included in <algorithm></code>

Alternatively, on Linux systems, one can use mlock(v.data(), v.size() * sizeof(v[0])); to force the pages into the address space. Refer to the man mlock manual page for further details.

The above is the detailed content of Why is std::vector Faster than std::array in Iteration?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn