Emptiness tested through size or length instead of isEmpty
ID |
scala.performance.container_size_empty |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Scala |
Description
Emptiness is being decided from a full element count. On a linked collection such as List, length/size walks every element only for the result to be compared against zero. Use isEmpty or nonEmpty, which stop at the first element and state the intent directly.
Rationale
Emptiness is being decided from a full element count. On a linked collection such as List, length/size walks every element only for the result to be compared against zero. Use isEmpty or nonEmpty, which stop at the first element and state the intent directly.
The following code illustrates the pattern detected by this rule:
class ContainerSizeEmpty {
def hasNoItems(items: List[String]): Boolean = {
// FLAGGED: Emptiness tested through size or length instead of isEmpty
items.length == 0
}
}