Scala

Scala

By DeepSource

Use .lastOption to access the last element SC-P1001
Performance

Certain Scala structures such as List implement methods such as .reverse that allows you to reverse the contents of a structure. This however can be an expensive operation and depends upon the kind of structure and the number of elements in it. Therefore, directly accessing the last element via .lastOption is more concise and performant than reversing an entire collection and then accessing the first element.

Use .isEmpty or .nonEmpty to check if structure is empty SC-P1002
Performance

Scala allows you to use comparison operators such as == and != against List() and Set() to check if a structure is empty or not. However, this method is considered to be in-efficient as doing so instantiates a new and empty structure which is only disposed off by the GC when deemed appropriate, thus causing an additional overhead. Therefore, it is suggested that you use the structures' .isEmpty and .nonEmpty methods to check if the respective structures are empty or not.

Consider filtering first and then sorting SC-P1003
Performance

Algorithms such as sorting and filtering depend upon size of a structure, i.e. the number of elements in a structure. If you wish to arrange your elements in a specified order and select only a subset of these elements, it is suggested that you first filter the elements according to your criteria and then sort them as this potentially reduces the number of elements to be sorted, thus reducing the overall time spent performing this operation.

Consider using the appropriate overloaded method when searching for a single char SC-P1004
Performance

Methods such as String.indexOf and String.lastIndexOf allow you to search for an occurrence of either a single char or a substring within a String. If you'd like to search for an occurrence of a single char, it is recommended that you use the appropriate method that takes a Char as a parameter rather than a String as the former approach is more performant and recommended.

Calling List.size is inefficient SC-P1005
Performance

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
}