Main Content

Expensive use of container's size method

A container's size() method is used for checking emptiness instead of its empty() method, which is more efficient

Since R2022b

Description

This defect occurs when you call a container's size() method to check if the container is empty. For instance:

std::list l;
//...
if(l.size()==0)// Inefficient
//..
when you use the method to check whether the container is empty, Polyspace® flags l.size().

Risk

A container's size() method might be expensive if you use C++ version predating C++11. Using such a method to check for emptiness of a container is unnecessarily expensive and might result in inefficient code.

Fix

To check a container's emptiness, use its empty() method instead. For instance:

std::list l;
//...
if(l.empty())// Efficient
//..
In C++ version predating C++11, the empty() methods of STL containers are O(1) but the size() method is O(N). When checking for emptiness, the empty() method is the more efficient solution.

If you are using C++11 or later, the size() method of an STL container is as efficient as the empty() method. Because the empty() method clearly communicates the developers intent, it is a good practice to use it when checking if a container is empty.

Performance improvements might vary based on the compiler, library implementation, and environment that you are using.

Examples

expand all

#include <list>
#include <algorithm>
#include <string>

// is_container_empty
bool is_container_empty(const std::list<std::string> &mylist)
{
   return mylist.size() != 0;          
}

In this example, the function is_container_empty() checks whether the list mylist is empty by comparing the output of mylist.size() to zero. This method of checking empliness of a container is inefficient. Polyspace flags the call to mylist.size().

Correction — Use the Containers empty() Method

To resolve this defect, use the empty() method of the container when checking for emptiness.

#include <list>
#include <algorithm>
#include <string>

// is_container_empty
bool is_container_empty(const std::list<std::string> &mylist)
{
   return mylist.empty();          
}

Result Information

Group: Performance
Language: C++
Default: Off
Command-Line Syntax: EXPENSIVE_CONTAINER_EMPTINESS_CHECK
Impact: Low

Version History

Introduced in R2022b