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 thevectormemory, instead just sets the internal “size” flag to0, so that method will be faster.