Secondary constructors in Kotlin - Time & Space Complexity
Let's see how the time it takes to run code with secondary constructors changes as we create more objects.
We want to know how the number of objects affects the work done during construction.
Analyze the time complexity of the following code snippet.
class Person {
var name: String
var age: Int
constructor(name: String) {
this.name = name
this.age = 0
}
constructor(name: String, age: Int) {
this.name = name
this.age = age
}
}
fun createPeople(n: Int): List {
val list = mutableListOf()
for (i in 1..n) {
list.add(Person("Person $i", i))
}
return list
}
This code defines a class with two ways to create objects and then makes a list of many such objects.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that creates and adds each Person object to the list.
- How many times: Exactly n times, once for each Person created.
Each new person means one more object created and added to the list.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations and additions |
| 100 | 100 creations and additions |
| 1000 | 1000 creations and additions |
Pattern observation: The work grows directly with the number of people created.
Time Complexity: O(n)
This means if you double the number of people, the time to create them roughly doubles too.
[X] Wrong: "Secondary constructors make object creation slower in a way that changes time complexity."
[OK] Correct: Secondary constructors just offer different ways to build objects, but creating each object still takes constant time, so total time grows linearly with the number of objects.
Understanding how object creation scales helps you explain performance clearly and shows you know how constructors affect program speed.
What if we added a loop inside the constructor that runs m times? How would the time complexity change?