Companion objects as static alternatives in Kotlin - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Calling the companion object function
addinside a loop. - How many times: 1000 times, once per loop iteration.
Each time we increase the number of calls, the total work grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to add |
| 100 | 100 calls to add |
| 1000 | 1000 calls to add |
Pattern observation: The total work grows evenly as the number of calls increases.
Time Complexity: O(n)
This means the time to run grows directly with the number of times we call the companion object function.
[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.
Understanding how companion objects behave helps you explain performance when using static-like features in Kotlin.
"What if we replaced the companion object function with an inline function? How would the time complexity change?"