N
N
Nikita2022-04-12 23:59:53
C++ / C#
Nikita, 2022-04-12 23:59:53

What's the speed difference between vector.resize and vector.reserve (C++)?

Let's say we have this code:

std::vector<int> vector(10000);
for (int i = 0; i < 10000; i = i + 1) vector[i] = i;

Will it be faster than this code:
std::vector<int> vector;
vector.reserve(10000);
for (int i = 0; i < 10000; i = i + 1) vector.push_back(i);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Armenian Radio, 2022-04-13
@gth-other

If you disassemble, you can see that in the lower code there is a conditional operator that checks if it's time to resize the array. There is no such thing in the above code.
A smarter optimizer might end up throwing out that check as well, and then the code would be identical.
Total, it is a theoretical question like "who has a better optimizer". In practice, the top code is more likely to become faster even with poor optimization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question