Creating instances without new keyword in Kotlin - Performance & Efficiency
We want to understand how the time it takes to create objects changes as we create more of them without using the new keyword.
How does the cost grow when making many instances this way?
Analyze the time complexity of the following code snippet.
class Person(val name: String)
fun createPeople(names: List): List {
return names.map { Person(it) }
}
This code creates a list of Person objects from a list of names without using the new keyword explicitly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a
Personinstance for each name in the list. - How many times: Once for each element in the input list
names.
Each name causes one new Person to be created, so the work grows directly with the number of names.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 creations |
| 100 | 100 creations |
| 1000 | 1000 creations |
Pattern observation: The number of operations grows in a straight line with input size.
Time Complexity: O(n)
This means the time to create all instances grows directly in proportion to how many you make.
[X] Wrong: "Creating instances without the new keyword is faster or slower in a way that changes time complexity."
[OK] Correct: The keyword new is just syntax; the actual work of creating each object still happens once per item, so time grows the same way.
Understanding how object creation scales helps you reason about performance in real apps, especially when working with collections and data transformations.
"What if we changed map to a recursive function creating instances? How would the time complexity change?"