random
random

Reputation: 353

Performance - checking if container is empty before doing operations on it?

Is there a significant difference between doing this...

if ( !myVector.empty()) {
  for ( unsigned int i = 0; i < myVector.size(); ++i ) {
    // do stuff
  }
}

and this

for ( unsigned int i = 0; i < myVector.size(); ++i ) {
  // do stuff
}

if the vector is empty? What is the cost of this on an empty vector?

Upvotes: 1

Views: 510

Answers (5)

shader
shader

Reputation: 447

You are right, empty() is faster than comparing size() against zero

That's a rule mentioned by Effective STL

Upvotes: 0

Bill Lynch
Bill Lynch

Reputation: 81916

vector::size is required to be O(1) complexity. So for any reasonable implementation, for VECTORS, you can skip the calls to empty().

A reasonable implementation of a vector would look something like this:

class vector { 
    private:
        size_t m_size;

    public:
        size_t size() {
            return m_size;
        }

        bool empty() {
            return m_size == 0;
        }
};

Upvotes: 1

James
James

Reputation: 2474

i < myVector.size();

Will cause the loop to die before running on an empty vector. Anything more is redundant.

Upvotes: 0

Jagannath
Jagannath

Reputation: 4025

Since you asked for performance, why do you need to call the method size in for loop? Why don't you get the value before the loop starts ?

size_t size = myvector.size();

As far as your question, others have already replied.

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Both size and empty are constant time for vectors. So most of the time (non-empty vectors), the first one just adds a small, constant amount of work. The second is clearly cleaner, and probably negligibly more efficient on average.

Upvotes: 2

Related Questions