I'm aware that vectors with resize or/and push_back are slower than plain arrays due to additional creations/copies of objects. Most questions asked before about slowness of vectors are about resize/push_back slowness. Usual advice is to use reserve+emplace_back because they're faster than push_back.
I've done some benchmarks according to whiches reserve+emplace_back are much slower than plain arrays. Why? Am I missing something that makes comparison unfair?
Code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <vector>
#include <chrono>
#include <string>
#include <algorithm>
#include <climits>
using tp = std::chrono::steady_clock::time_point;
class Time {
public:
static void show(tp t1, tp t2) { //time passed since t1
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count() << '\t';
printf("nanoseconds \n");
}
tp add() {
tp p = std::chrono::steady_clock::now();
return p;
}
};
int main()
{
Time time;
const int VSIZE = 1000000;
auto t1 = time.add();
double vsizearr[VSIZE];
for (auto i = 0; i < VSIZE; i++) {
vsizearr[i]=i;
asm volatile("" : : : "memory"); //doesn't allow compiler to erase the loop
}
auto t2 = time.add();
std::vector<double> second;
second.reserve(VSIZE);
for (auto i = 0; i < VSIZE; i++) {
second.emplace_back(i);
asm volatile("" : : : "memory"); //doesn't allow compiler to erase the loop
}
auto t3 = time.add();
time.show(t1, t2);
time.show(t2, t3);
return 0;
}
Benchmarks results:
Windows 10, C++17, LLVM-clang, -O1
306300 nanoseconds
1824700 nanoseconds
Ubuntu 20.04, C++17, g++ and clang
root@vlad-VirtualBox:/home/vlad/Documents clang++ -O1 -std=c++17 -o test test.cpp
root@vlad-VirtualBox:/home/vlad/Documents ./test
284340 nanoseconds
3115997 nanoseconds
root@vlad-VirtualBox:/home/vlad/Documents g++ -O1 -std=c++17 -o test test.cpp
root@vlad-VirtualBox:/home/vlad/Documents ./test
284340 nanoseconds
3145702 nanoseconds
-O3 results are about the same as -O1.