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 //..
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 //..
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
Result Information
Group: Performance |
Language: C++ |
Default: Off |
Command-Line Syntax:
EXPENSIVE_CONTAINER_EMPTINESS_CHECK
|
Impact: Low |
Version History
Introduced in R2022b
See Also
Topics
- Interpret Bug Finder Results in Polyspace Desktop User Interface
- Interpret Bug Finder Results in Polyspace Access Web Interface (Polyspace Access)
- Address Results in Polyspace User Interface Through Bug Fixes or Justifications
- Address Results in Polyspace Access Through Bug Fixes or Justifications (Polyspace Access)