Inline functions and performance in Kotlin - Time & Space Complexity
We want to see how using inline functions affects the speed of running code.
Does inlining make the program faster or slower as the input grows?
Analyze the time complexity of the following code snippet.
inline fun repeatAction(times: Int, action: () -> Unit) {
for (i in 1..times) {
action()
}
}
fun main() {
repeatAction(5) {
println("Hello")
}
}
This code runs an action multiple times using an inline function to avoid extra call overhead.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop running the action multiple times.
- How many times: Exactly as many times as the input number
times.
Each time we increase the input times, the action runs that many more times.
| Input Size (times) | Approx. Operations |
|---|---|
| 10 | 10 actions run |
| 100 | 100 actions run |
| 1000 | 1000 actions run |
Pattern observation: The work grows directly with the input size.
Time Complexity: O(n)
This means the time to run the code grows in a straight line as the input number grows.
[X] Wrong: "Inlining changes the time complexity to be faster than linear."
[OK] Correct: Inlining removes function call overhead but does not reduce how many times the action runs, so the total work still grows linearly.
Understanding how inline functions affect performance helps you explain real code speed and efficiency clearly.
"What if the action itself contained a loop that runs n times? How would the time complexity change?"