0
0
Kotlinprogramming~5 mins

Companion objects as static alternatives in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Companion objects as static alternatives
O(n)
Understanding Time Complexity

We want to understand how using companion objects affects the time it takes to run code.

Specifically, we ask: how does accessing companion object members scale as the program runs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Calculator {
    companion object {
        fun add(a: Int, b: Int): Int {
            return a + b
        }
    }
}

fun main() {
    repeat(1000) {
        Calculator.add(it, it * 2)
    }
}
    

This code calls a companion object function many times to add numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the companion object function add inside a loop.
  • How many times: 1000 times, once per loop iteration.
How Execution Grows With Input

Each time we increase the number of calls, the total work grows in direct proportion.

Input Size (n)Approx. Operations
1010 calls to add
100100 calls to add
10001000 calls to add

Pattern observation: The total work grows evenly as the number of calls increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of times we call the companion object function.

Common Mistake

[X] Wrong: "Using companion objects makes function calls instantaneous or free."

[OK] Correct: Even though companion objects act like static members, each function call still takes time, so more calls mean more work.

Interview Connect

Understanding how companion objects behave helps you explain performance when using static-like features in Kotlin.

Self-Check

"What if we replaced the companion object function with an inline function? How would the time complexity change?"