Named companion objects in Kotlin - Time & Space Complexity
Let's explore how the time it takes to run code with named companion objects changes as the program grows.
We want to see how the number of operations changes when using named companion objects in Kotlin.
Analyze the time complexity of the following code snippet.
class Example {
companion object Factory {
fun createList(n: Int): List {
val list = mutableListOf()
for (i in 1..n) {
list.add(i)
}
return list
}
}
}
fun main() {
val numbers = Example.Factory.createList(1000)
}
This code defines a named companion object Factory inside a class Example. It creates a list of numbers from 1 to n.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds numbers to the list.
- How many times: It runs exactly n times, once for each number from 1 to n.
As n grows, the loop runs more times, so the work grows in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: Doubling n doubles the work because each number is added once.
Time Complexity: O(n)
This means the time to create the list grows directly with the number of items you want to add.
[X] Wrong: "Using a named companion object makes the code slower because it adds extra steps."
[OK] Correct: The companion object is just a way to organize code. It does not add loops or repeated work, so it does not affect how the time grows with input size.
Understanding how companion objects work and their impact on performance shows you know how Kotlin organizes code and how that relates to efficiency.
"What if the createList function used recursion instead of a loop? How would the time complexity change?"