As asked
Scala encourages immutability by default. What are the performance implications of using immutable data structures, and when is a mutable local variable (var) or a mutable collection acceptable?
Sample answer outline
Immutable data structures create copies on modification, which costs allocation and GC. For large collections modified in a tight loop, this is a real cost. Acceptable uses of mutable: a local var inside a pure function that is not visible outside (like a loop accumulator), or a mutable Builder (StringBuilder, ArrayBuffer) used to build a result that is then returned as immutable. The key is that mutation is not observable by callers. Persistent data structures like Vector use structural sharing to reduce copying costs.
Expect these follow-ups
- What is structural sharing in a persistent data structure and how does Vector[A] implement it?
- When would you reach for a scala.collection.mutable.HashMap over an immutable Map in a hot path?