When you call empty(), it clearly communicates the code’s intention, which is to check if the collection is empty. Using size()
== 0 for this purpose is less direct and makes the code slightly more complex.
Moreover, in the standard library, depending on the implementation, the size() method can have a time complexity of O(n)
where n is the number of elements in the collection. On the other hand, empty() simply checks if there is at least one
element in the collection, which is a constant time operation, O(1). Note that this rule also identifies similar method names in
user-defined types, where the semantics and complexity may differ.
void fun(const std::vector<int> &myVector) {
if (myVector.size() == 0) { // Noncompliant
// do something
}
}
Prefer using empty() or to test for emptiness over size().
void fun(const std::vector<int> &myVector) {
if (myVector.empty()) {
// do something
}
}