The difference is due to memory pages of array
not being resident in process address space (global scope array is stored in .bss
section of the executable that hasn’t been paged in, it is zero-initialized). Whereas vector
has just been allocated and zero-filled, so its memory pages are already present.
If you add
std::fill_n(v.data(), n, 1); // included in <algorithm>
as the first line of main
to bring the pages in (pre-fault), that makes array
time the same as that of vector
.
On Linux, instead of that, you can do mlock(v.data(), v.size() * sizeof(v[0]));
to bring the pages into the address space. See man mlock
for full details.