SC

Scala Performance

Scala JVM performance patterns including collection selection, lazy evaluation, and allocation avoidance

Details

Language / Topic
scalaScala
Category
Performance

Rules

balanced
- Use `Vector` for indexed random access, `List` for prepend-heavy workloads, and `ArrayBuffer` for mutable batch construction.
- Use `.view` to create a lazy wrapper over collections — chain `.map`/`.filter` without allocating intermediate collections.
- Annotate hot recursive methods with `@tailrec` to ensure the compiler converts them to loops and avoids stack overflow.
- Avoid boxing primitives: use `Array[Int]` over `Array[Integer]` and `@specialized` annotations on generic classes that process numeric types.
- Use `LazyList` (formerly `Stream`) for potentially-infinite or expensive-to-compute sequences — elements are evaluated only on demand.
- Profile with JMH (`sbt-jmh`) before optimising — Scala's optimizer, the JIT, and collection implementations often behave counter-intuitively.
- Prefer `StringBuilder` over string concatenation (`+`) in loops — each `+` allocates a new `String` object on the heap.