🎓 A1Learner
🔍
0 of 48 lessons completed

Scala Collection Performance

Performance guidance is advice about which collection shape fits each kind of work. It helps you pick a shape before speed ever becomes a problem.

Prepend and append build the same list differently

Both lines build a list, but the prepend form is the cheap one for a List. The append form walks the whole list first.

@main def main(): Unit =
  val a = 0 :: List(1, 2, 3)
  val b = List(1, 2, 3) :+ 4
  println(a)
  println(b)

Vector and List both answer by position

Both lines print 30, but they reach it differently. Vector jumps straight to the position, while a List walks from the front.

@main def main(): Unit =
  val v = Vector(10, 20, 30)
  val xs = List(10, 20, 30)
  println(v(2))
  println(xs(2))

A Map lookup answers by key

The lookup finds the value for a key without walking the entries. That is why a Map fits lookups on large collections.

@main def main(): Unit =
  val m = Map("ana" -> 90, "bo" -> 75)
  println(m.size)
  println(m.getOrElse("bo", 0))

Example

@main def main(): Unit =
  val scores = Map("ana" -> 90, "bo" -> 75)
  val xs = List(1, 2)
  val v = Vector(10, 20, 30)
  println(scores.getOrElse("ana", 0))
  println(0 :: xs)
  println(v(2))

Key points

  • Prepend: adding to the front of a List is cheap, because the new head simply points at the old list.
  • Append: adding to the end of a List walks the whole list to reach the end.
  • Index: Vector finds an item by position quickly, while a List walks from the front to reach it.
  • Lookup: a Map finds a value by key quickly, even when the map is large.
  • Small: for a tiny collection, any shape works well, so pick the clearest one.

In this example, each job uses the shape that fits it: a Map for a lookup by name, a List prepend for adding to the front, and a Vector for reading by position. The three printed answers show each shape doing its own job.

Note

this lesson gives guidance only, because timings change from run to run and prove nothing stable.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

You need to read items by position again and again from a long collection. Which shape fits best?