Expensive use of container's count method
The function member count()
of a container is used for checking
if a key is present, leading to inefficient code
Since R2021b
Description
This defect is raised when the function member count()
of these
containers is called for checking if a key is present:
std::multimap
std::multiset
std::unordered_multiset
std::unordered_multimap
When checking containment, you convert the output of the container's
count()
method to a bool
, or compare it to either
0
or 1
.
Risk
The count
function of the preceding containers performs a linear
search and finds all the instances of a key in the container. When checking if a key is
present in a container, performing an exhaustive search for every instance of the key is
unnecessary and inefficient.
Fix
To fix this defect, call the member find
or
contains
function of a container when checking for containment. These
functions stop searching for a key as soon as one instance of the key is found. These
functions check containment more efficiently compared to the count
function.
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_COUNT |
Impact: Medium |
Version History
Introduced in R2021b
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)