Original Conclusion Misconception
Initially, a flawed benchmark suggested that std::array iteration was faster than std::vector iteration. However, upon correcting the benchmark, it emerged that std::vector was significantly faster.
Benchmark Implementation
To ensure accuracy, the benchmark employed several improvements:
Results and Explanation
The benchmark results revealed that std::vector iteration completed in approximately 30 milliseconds, while std::array iteration took about 99 milliseconds.
The disparity stems from the memory page behavior. In the benchmark, the std::array was in the .bss section of the executable (with zero initialization), so its memory pages were not loaded into the process address space. Conversely, the std::vector had been allocated and zero-filled, resulting in page presence.
Solution
Pre-faulting the std::array's pages by zero-filling or using mlock() on Linux brings its pages into the address space, equating its iteration speed with that of std::vector.
The above is the detailed content of Why is std::vector iteration faster than std::array iteration despite initial benchmarks suggesting otherwise?. For more information, please follow other related articles on the PHP Chinese website!