Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's faster: recreate or clear()?

Tags:

c++

vector

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);
    }
}
like image 787
blubberbernd Avatar asked Sep 08 '11 16:09

blubberbernd


3 Answers

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.

like image 50
Chad Avatar answered Nov 17 '22 03:11

Chad


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.

like image 2
Praetorian Avatar answered Nov 17 '22 03:11

Praetorian


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.

like image 1
Robᵩ Avatar answered Nov 17 '22 05:11

Robᵩ