Skip to Content
Course content

169: Collection Performance Characteristics

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

Should I ever actually use a LinkedList over an ArrayList?

In short: almost never. I know some old-school textbooks will tell you that LinkedList is better for adding or removing elements from the middle of the list. On paper, that's true because it doesn't have to "shift" elements. But in the real world of the JVM, ArrayList usually wins anyway.

The reason is CPU caching. ArrayList stores elements in a contiguous block of memory. Your CPU loves this; it can predict what's coming next and load it into the cache. A LinkedList scatters its nodes all over the heap, forcing the CPU to jump around, which causes "cache misses" that kill performance.

// Unless you are doing an absurd amount of insertions at the very front 
// of a massive list, just stick with the default:
val users = mutableListOf<User>() // This is an ArrayList under the hood

If you find yourself needing to add/remove from both ends frequently, use an ArrayDeque. It gives you the performance of a queue without the memory overhead of a linked list.

I have a list of IDs; is it worth converting it to a Set just to check if an item exists?

This depends entirely on the size of your data and how many times you're doing the check. Checking if an item exists in a List is an $O(n)$ operation. That means if you have 10,000 IDs, Kotlin might have to check all 10,000 before it realizes the ID isn't there.

A HashSet, however, is $O(1)$. It doesn't matter if you have ten items or ten million; the lookup time is virtually the same. If you're doing a single check on a tiny list, don't bother with the conversion—the overhead of creating the Set will cost more than the search. But if you're inside a loop, it's a massive win.

val blacklist = listOf("id_1", "id_5", "id_20") // imagine this is 10k items

// BAD: This is O(n * m). It's a performance nightmare for large lists.
incomingIds.filter { id -> blacklist.contains(id) }

// GOOD: Convert to Set first. Now it's O(n).
val blacklistSet = blacklist.toSet() 
incomingIds.filter { id -> blacklistSet.contains(id) }

I keep hearing that Sequence is "faster" than Iterable. When does it actually make a difference?

I see developers using asSequence() everywhere, even when it actually makes their code slower. Here is the deal: standard Kotlin collection functions (like filter and map) are eager. They create a brand new intermediate list at every single step.

If you have a list of 100,000 items and you filter it, then map it, then filter it again, you've just created three different lists in memory. That's a lot of garbage for the GC to clean up. A Sequence is lazy. It processes one item through the entire chain before moving to the next item, meaning no intermediate lists are created.

But—and this is a big but—there is an overhead to setting up the sequence machinery. If your list is small (say, under a few hundred items), the eager approach is usually faster. I generally only reach for sequences when I'm dealing with very large datasets or "infinite" streams of data.

val largeDataset = (1..1_000_000).toList()

// This creates two intermediate lists of potentially 1M items each.
val result = largeDataset
    .filter { it % 2 == 0 } 
    .map { it * 2 }
    .first()

// This processes one item at a time. It stops as soon as it finds the first match.
val sequenceResult = largeDataset.asSequence()
    .filter { it % 2 == 0 }
    .map { it * 2 }
    .first()



📋 Practical Task

Optimizing the Log Error Deduplicator

You are building a log processing tool. You have a massive list of LogEntry objects. Your goal is to find the first 5 unique "Critical" error messages, but only for logs that occurred in the last 24 hours.

The Challenge: Implement a function getTopCriticalErrors(logs: List<LogEntry>): List<String>. The input list can contain up to 500,000 entries. To ensure maximum performance and minimum memory pressure, you must:

  • Avoid creating large intermediate lists (use the appropriate tool for lazy evaluation).
  • Ensure the "uniqueness" check is performed using a collection with $O(1)$ lookup time.
  • Stop processing the moment you have found 5 unique errors.

Define a simple LogEntry data class with level: String, message: String, and timestamp: Long to make your code runnable.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.