Answer the question
In order to leave comments, you need to log in
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;
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
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 questionAsk a Question
731 491 924 answers to any question