Scala

Scala

Made by DeepSource

Calling List.size is inefficient SC-P1005

Performance
Major

Scala's List data-structure is an immutable sequence of elements, implemented as a linked list. Therefore, methods such as .size have a complexity of O(n). Repeatedly calling such methods can impact the performance of your application. Therefore, it is suggested that you use a different structure such as an Array or an ArrayBuffer depending whichever that suites your needs.

Benchmarks -

val numsList = (1 to 1000000).toList

// 2713250ns
time {
  numsList.size
}

val numsArray = (1 to 1000000).toBuffer

// 11750ns
time {
  numsArray.size
}

Bad practice

val numbers = List(1, 2, 3)
val size    = numbers.size

Recommended

val numbers = Array(1, 2, 3)
val size    = numbers.size