开发者

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 vecto开发者_开发问答r is empty? What is the cost of this on an empty vector?


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.


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;
        }
};


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.


i < myVector.size();

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


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

That's a rule mentioned by Effective STL

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜