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