Iterating collections with forEach in Kotlin - Time & Space Complexity
When we use forEach to go through a collection, we want to know how the time it takes changes as the collection grows.
We ask: How does the work increase when the list gets bigger?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach { number ->
println(number)
}
This code goes through each number in the list and prints it out.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forEachloop visits each item once. - How many times: Exactly once per item in the list.
As the list gets bigger, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Using forEach is slower than a regular for loop because it has extra overhead."
[OK] Correct: Both do the same number of steps over the list. The difference is tiny and does not change how time grows with list size.
Understanding how forEach scales helps you explain your code choices clearly and shows you know how loops affect performance.
"What if we nested a forEach inside another forEach? How would the time complexity change?"