Marco A.
Marco A.

Reputation: 43662

What is more efficient: vector.clear() or if(vector.empty()) clear();?

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

Answers (2)

Sebastian Redl
Sebastian Redl

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

Martin Schlott
Martin Schlott

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

Related Questions