Home > Backend Development > C++ > body text

Why is std::vector iteration faster than std::array iteration despite initial benchmarks suggesting otherwise?

Susan Sarandon
Release: 2024-11-01 15:35:02
Original
256 people have browsed it

Why is std::vector iteration faster than std::array iteration despite initial benchmarks suggesting otherwise?

Why std::vector Iteration Surpasses std::array Iteration

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:

  • Result utilization to prevent loop optimization
  • -O3 optimization flag for enhanced speed
  • std::chrono for isolated loop measurement without static variables interference

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!