Object declaration syntax in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code changes when we use Kotlin's object declaration syntax.
We want to know how the program's work grows as we create or use objects this way.
Analyze the time complexity of the following code snippet.
object Logger {
fun log(message: String) {
println(message)
}
}
fun main(n: Int) {
for (i in 1..n) {
Logger.log("Message $i")
}
}
This code defines a single object Logger and calls its log function n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling Logger.log inside a loop.
- How many times: Exactly n times, once per loop iteration.
Each time we increase n, the number of log calls grows the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 log calls |
| 100 | 100 log calls |
| 1000 | 1000 log calls |
Pattern observation: The work grows directly with n, so doubling n doubles the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of times we call the log function.
[X] Wrong: "Since Logger is a single object, calling its method many times is constant time."
[OK] Correct: Even though the object is created once, each method call still takes time, so more calls mean more total time.
Understanding how repeated calls to a single object affect time helps you explain performance clearly and confidently in interviews.
"What if we created a new Logger object inside the loop each time instead of using the object declaration? How would the time complexity change?"