Companion vs top-level functions decision in Kotlin - Performance Comparison
When deciding between companion and top-level functions in Kotlin, it's important to understand how their time complexity behaves.
We want to know how the choice affects the speed of running the functions as the program grows.
Analyze the time complexity of calling companion object functions versus top-level functions.
class Example {
companion object {
fun companionFunction(n: Int): Int {
var sum = 0
for (i in 1..n) {
sum += i
}
return sum
}
}
}
fun topLevelFunction(n: Int): Int {
var sum = 0
for (i in 1..n) {
sum += i
}
return sum
}
This code shows two functions doing the same work: summing numbers from 1 to n.
One is inside a companion object, the other is a top-level function.
Both functions have the same repeating operation:
- Primary operation: A loop that adds numbers from 1 to n.
- How many times: Exactly n times for each function call.
The difference is only where the function lives, not what it does repeatedly.
As n grows, the number of additions grows the same way for both functions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with n, no matter where the function is placed.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size, whether it is a companion or top-level function.
[X] Wrong: "Companion functions are slower because they are inside a class."
[OK] Correct: The location of the function does not add extra loops or work; the time depends on what the function does, not where it lives.
Understanding that function placement does not change time complexity helps you focus on what really matters: the work inside the function.
This skill shows you can separate design choices from performance impact clearly.
What if the companion function called another function inside the class that also loops over n? How would the time complexity change?