0
0
Kotlinprogramming~5 mins

Inline functions and performance in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Inline functions and performance
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each time we increase the input times, the action runs that many more times.

Input Size (times)Approx. Operations
1010 actions run
100100 actions run
10001000 actions run

Pattern observation: The work grows directly with the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line as the input number grows.

Common Mistake

[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.

Interview Connect

Understanding how inline functions affect performance helps you explain real code speed and efficiency clearly.

Self-Check

"What if the action itself contained a loop that runs n times? How would the time complexity change?"