.isEmpty
or .nonEmpty
instead of .size
for List
s SC-R1025Scala's List
data structure is an immutable sequence of elements, implemented as a linked list. Because of this, methods such as .size
have a complexity of O(n). Repeatedly calling these methods can impact the performance of your application. Therefore, it is suggested that you use methods such as .isEmpty
or .nonEmpty
to check if a list is empty rather than relying on .size
.
Benchmarks -
val numsList = (1 to 1000000).toList
// 2713250ns
time {
numsList.size
}
val numsArray = (1 to 1000000).toBuffer
// 11750ns
time {
numsArray.size
}
def processElements(elements: List[Int]): Unit = {
if (elements.size != 0) {
//
}
}
def processElements(elements: List[Int]): Unit = {
if (elements.nonEmpty) {
//
}
}