SAM conversions for Java interfaces in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code changes when using SAM conversions for Java interfaces in Kotlin.
Specifically, how does the cost grow when we create many instances using SAM conversions?
Analyze the time complexity of the following code snippet.
fun createRunnables(n: Int): List {
return List(n) { i ->
Runnable { println("Running task $i") }
}
}
This code creates a list of n Runnable objects using SAM conversion from a lambda.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a Runnable instance inside a loop.
- How many times: Exactly
ntimes, once per list element.
Each Runnable is created once per loop iteration, so the total work grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 Runnable creations |
| 100 | 100 Runnable creations |
| 1000 | 1000 Runnable creations |
Pattern observation: The work increases evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create all Runnable instances grows in a straight line with the number of instances.
[X] Wrong: "SAM conversions make instance creation instant or free."
[OK] Correct: Each SAM conversion still creates a new object, so the time grows with how many you make.
Understanding how SAM conversions affect performance helps you write clear and efficient Kotlin code when working with Java interfaces.
What if we reused a single Runnable instance instead of creating one per loop? How would the time complexity change?