std::vector Insertion: emplace_back vs push_back
Question 10 / 51 • Correct so far: 0 (0 answered)
Push Back
std::vector<Payload> buildPayloads(int n) {
std::vector<Payload> v;
v.reserve(n);
for (int i = 0; i < n; ++i)
v.push_back(Payload{i, TAG_TEXT, 'x'});
return v;
}
std::vector<Payload> v = buildPayloads(kInsertCount); Emplace Back
std::vector<Payload> buildPayloads(int n) {
std::vector<Payload> v;
v.reserve(n);
for (int i = 0; i < n; ++i)
v.emplace_back(i, TAG_TEXT, 'x');
return v;
}
std::vector<Payload> v = buildPayloads(kInsertCount); Shared test data (shared-setup)
struct Payload {
std::array<char, 2048> data;
std::string tag;
int id;
Payload(int i, const std::string& t, char fill) : tag(t), id(i) { data.fill(fill); }
};
constexpr int kInsertCount = 16;
static const std::string TAG_TEXT = "payload-tag-for-vector-benchmark"; Which snippet is faster?
Snippet B is faster. push_back constructs a temporary Payload then moves it into the vector; emplace_back constructs the Payload directly in the vector's storage, skipping the temporary. The extra move is visible here because Payload contains a 2 KB array and a string.
Benchmark results
| Snippet | CPU time / iteration | Speedup |
|---|---|---|
| Emplace Back | 456 ns | 1.4× |
| Push Back | 640 ns | 1.0× |
Explore the source
Open in Compiler ExplorerQuiz complete. You can return to the question list to restart and compare.