Next: High Integrity CPP Guideline 17.7  Up: 17 Standard Template Library (STL)  Previous: High Integrity CPP Rule 17.5  Contents

High Integrity CPP Guideline 17.6   Use empty() instead of checking size() against zero.

Justification

Testing empty() and comparing size() to zero are the same thing, however for some containers it is expensive to calculate the number of elements so it is less efficient to compare the size to zero. It is always better to use empty when testing if a container has elements.

   
   std::list< Node > myList;
   
   if ( false == myList.empty() )   // constant time test
   {
      doSomething();
   }
   
   if ( 0 == myList.size() )        // linear complexity operation
   {
      doSomethingWheneverFinishedCountingAllNodes();
   }
Reference

Effective STL Item 4;


HICPP VERSION 2.4  http://www.codingstandard.com   Copyright: © 2007 THE PROGRAMMING RESEARCH GROUP