I have a question about the performance of the std::vector<> in C++. Is it faster to reuse the same vector by calling its clear() method or it it faster to recreate the vector?
The following example is no real life code, it's only for making clear what the question is:
//Example ONE: is this faster
std::vector<int> foo;
for(int i = 0; i < 100; ++i)
{
foo.clear();
for(int j = 0; j < 100; ++j)
{
foo.push_back(i+j);
}
}
//Example TWO: or is that faster?
for(int i = 0; i < 100; ++i)
{
std::vector<int> foo;
for(int j = 0; j < 100; ++j)
{
foo.push_back(i+j);
}
}
The clear()
cannot by its contract deallocate the vector
memory, instead just sets the internal "size" flag to 0
, so that method will be faster.
It depends on the implementation of std::vector
in the C++ standard library that you're using, but it is likely that the first case will be faster because most implementations do not actually free allocated memory when you call std::vector::clear
. So the first one does not perform repeated allocations once the inner loop has been executed the first time.
Yes. No. The first one is faster, probably. It depends. The only useful answer comes from you profiling your own code in your own environment.
Try profiling your code to see what happens. Compiling your program at ideone reveals that, for one particular compiler/os/machine/run, your first example is 4x faster.
And this program shows an intermediate solution, which goes faster than #2, slower than #1, for this particular compiler/os/machine/run.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With