Data classes for value holders in Kotlin - Time & Space Complexity
Let's see how using data classes to hold values affects the time it takes to run code.
We want to know how the program's work grows when we create many data class objects.
Analyze the time complexity of the following code snippet.
data class Point(val x: Int, val y: Int)
fun createPoints(n: Int): List {
val points = mutableListOf()
for (i in 0 until n) {
points.add(Point(i, i * 2))
}
return points
}
This code creates a list of n Point objects, each holding two numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and adding a Point object inside a loop.
- How many times: Exactly
ntimes, once per loop iteration.
Each time we increase n, we do more work creating and storing points.
| 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 n. Double the input, double the work.
Time Complexity: O(n)
This means the time to create points grows in a straight line with the number of points.
[X] Wrong: "Creating data class objects is instant and doesn't add to time."
[OK] Correct: Each object creation takes time, so more objects mean more total time.
Understanding how creating many simple objects affects time helps you explain performance clearly in interviews.
"What if we changed the loop to create points only for even numbers? How would the time complexity change?"