Scala

Scala

Made by DeepSource

Consider using .isEmpty or .nonEmpty instead of .size for Lists SC-R1025

Anti-pattern
Major

Scala'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
}

Bad practice

def processElements(elements: List[Int]): Unit = {
  if (elements.size != 0) {
    //
  }
}

Recommended

def processElements(elements: List[Int]): Unit = {
  if (elements.nonEmpty) {
    //
  }
}