Reputation: 43662
As the subject states.. which version is more efficient and why?
std::vector a;
..
a.clear();
or
std::vector a;
..
if(!a.empty())
a.clear();
Upvotes: 0
Views: 614
Reputation: 72054
Efficiency aside, the fact that you managed to write a bug into this tiny snippet is proof that the first version is far superior. The less complicated the code, the better.
Upvotes: 12
Reputation: 4557
An empty vector is a valid vector. So the operation
a.clear();
is valid on an empty vector.
Test for emptiness before clear is unnecessary and time consuming, so the first one is more efficient.
Upvotes: 2