Editor's note:
Followup question with optimization enabled that times only the loop:
Why is iterating though `std::vector` faster than iterating though `std::array`?
where we can see the effect of lazy-allocation page faults in reading uninitialized BSS memory vs. dynamically-allocated + written memory that's initialized outside the timed loop.
I tried profiling this code:
#include <vector>
#include <array>
#include <stdio.h>
using namespace std;
constexpr int n = 400'000'000;
//vector<int> v(n);
array<int, n> v;
int main()
{
int res = 0;
for(int x : v)
res += x;
printf("%d\n", res);
}
On my machine, the array
version is faster than vector
.
The memory allocation is irrelevant in this case as it's only once.
$ g++ arrVsVec.cpp -O3
$ time ./a.out
0
real 0m0,445s
user 0m0,203s
sys 0m0,238s
$ g++ arrVsVec.cpp -O3
$ time ./a.out
0
real 0m0,749s
user 0m0,273s
sys 0m0,476s
I have found the disassembly is much more complicated for std::vector
: https://godbolt.org/z/111L5G
std::array
is free (takes zero time). – Callenderg++ -O3 arrVsVec.cpp
. Non-optimized "benchmarks" are completely worthless – Kristofororeserve
doesn't make any sense in this example as I'm allocating all the memory at once already – Beating