Reputation: 21763
Is
v.erase(v.begin(), v.end());
Just as fast as
v.clear();
?
I don't care about little overheads such as extra function calls etc, the compiler will inline that stuff.
The reason I ask is because I have code like the following:
v.erase(v.begin(), last_it);
last_it will usually be the end iterator, but not always. I know that erasing a vector not from the end has a cost, because later elements in the vector will need to be copied down. In the case where last_it is not the end iterator (rare), I can live with that. But I don't want to introduce such overhead when I basically want to clear the vector. So I considered writing my code like this:
if (last_it == v.end())
{
v.clear();
}
else
{
v.erase(v.begin(), last_it);
}
I would like to know whether this is necessary to avoid a performance penalty for erasing the whole vector. I would prefer to keep my code clear and use a single-line statement if there is no penalty.
Upvotes: 8
Views: 284
Reputation: 5334
Looking into the sourcecode of vector (refering to visual studio 2012 (code snippet below) or SGI (line 434) one), clear
is defined as:
void clear() _NOEXCEPT
{ // erase all elements
erase(begin(), end());
}
So i guess yes.
So in your case, I wouldn't use the if statement, and just do:
v.erase(v.begin(), last_it);
Upvotes: 8
Reputation: 11696
The problem is that there isn't a single answer to your question, because there is no single implementation of the C++ standard library that is used on all platforms. The only thing that is specified by the standard is the algorithmic complexity of the clear operation. Specifically, it can be constant time for trivially-destructible types; for types that require destruction, it will be linear in the number of destructions. That's the only guarantee that you get from the C++ standard.
The standard library is typically distributed as part of your compiler installation, so exact implementation details like this could very well vary from compiler to compiler. If you're only concerned with one single compiler version, you can come up with an answer, but recognize that it is subject to change if you ever change platforms.
Upvotes: 1
Reputation: 96243
Don't worry about this and write the obvious code using erase
. If you erase to the end there won't be any elements left to shift down so there should be minimal performance difference between the two, if any.
Upvotes: 8