Skip to Content
Course content

165: Common Scala Interview Questions on Collection Performance

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When I'm interviewing candidates for a senior Scala role, I rarely ask them to define a Trait or explain implicits—those are basics. Instead, I look for whether they actually understand the cost of the collections they're using. A lot of developers treat List, Vector, and Seq as interchangeable buckets for data, but in a high-throughput production system, that indifference is where your latency spikes come from.

The hidden tax of intermediate collections

Imagine you're processing a massive set of financial transactions to find high-value anomalies. You'll see a lot of candidates write something like this:

val highValueAnomalies = transactions
  .filter(_.amount > 10000)
  .map(t => t.copy(flagged = true))
  .filter(_.currency == "USD")
  .take(100)

On the surface, it's clean. It's functional. It's "the Scala way." But if transactions contains a million records, this code is a performance nightmare. Why? Because Scala's default collections are strict. The filter creates a brand new collection. Then the map creates another new collection. Then the second filter creates a third. You're allocating massive amounts of memory for intermediate results that you're just going to throw away a millisecond later. I've seen this lead to "Stop the World" GC pauses that bring entire microservices to their knees.

Lazy views and the magic of fusion

If you want to impress an interviewer—and more importantly, write efficient code—you need to talk about Views. By adding a single method call, you change the execution model from "do it now" to "do it when I actually ask for the result."

val highValueAnomalies = transactions.view
  .filter(_.amount > 10000)
  .map(t => t.copy(flagged = true))
  .filter(_.currency == "USD")
  .take(100)
  .toList

By calling .view, you're creating a non-strict collection. Instead of iterating through the whole list three times, Scala "fuses" these operations together. It takes the first element, runs it through the filter, then the map, then the filter, and if it survives, it puts it in the final list. As soon as it hits the 100th element (thanks to .take(100)), it stops entirely. You've gone from $O(3N)$ allocation and iteration to $O(K)$ where $K$ is just enough to satisfy your take requirement. It's a massive win.

Why your List append is killing your throughput

Another classic interview trap involves how we build collections. I often see people trying to build a result set by appending to a List inside a loop or a recursive function:

// The naive, slow way
var results = List[String]()
for (item <- items) {
  results = results :+ item.process() // O(n) append!
}

I can't stress this enough: List in Scala is a linked list. Appending to the end (:+) requires traversing the entire list to find the tail. If you do this in a loop, you've just turned a linear process into an $O(N^2)$ operation. If your list grows to 100,000 items, your app will effectively freeze.

If you need a collection that you can grow at the end, use a Vector. Vectors are implemented as 32-way hash array mapped tries, meaning appends are effectively constant time ($O(\log_{32} N)$). Or, if you're sticking with List, the professional move is to prepend (::), which is $O(1)$, and then call .reverse once at the very end. It sounds counter-intuitive to reverse the whole thing, but $O(N) + O(N)$ is infinitely better than $O(N^2)$.




📋 Practical Task

Exercise: Optimizing the High-Frequency Trade Filter

You have been handed a legacy module that processes a stream of Trade objects. The current implementation is causing memory pressure and is too slow for the production environment.

The Setup: Assume a case class Trade(id: Long, symbol: String, price: Double, volume: Int). You are given a List[Trade] containing 500,000 elements.

The Requirement: Rewrite the following logic to ensure that: 1. No intermediate collections are created during the filtering and transformation process. 2. The process stops as soon as the first 50 matching trades are found. 3. The final result is returned as a Vector for fast random access later in the pipeline.

// FIX THIS CODE
def getLargeTrades(trades: List[Trade]): List[Trade] = {
  trades
    .filter(_.volume > 1000)
    .map(t => t.copy(price = t.price * 1.01)) // simulate a price adjustment
    .filter(_.symbol == "AAPL")
    .take(50)
}

Submission: Provide the optimized getLargeTrades function implementing .view and the correct final collection conversion.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.