0
0
Kotlinprogramming~5 mins

Companion vs top-level functions decision in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Companion vs top-level functions decision
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.

How Execution Grows With Input

As n grows, the number of additions grows the same way for both functions.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The work grows directly with n, no matter where the function is placed.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

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.

Self-Check

What if the companion function called another function inside the class that also loops over n? How would the time complexity change?