Reference sharing and side effects in Swift - Time & Space Complexity
When we share references in Swift, changes to one object can affect others. This can impact how many operations happen when we modify data.
We want to see how the cost of these side effects grows as the data size increases.
Analyze the time complexity of the following code snippet.
class Box {
var value: Int
init(_ value: Int) { self.value = value }
}
func updateBoxes(_ boxes: [Box]) {
for box in boxes {
box.value += 1
}
}
let n = 10
let boxes = (1...n).map { Box($0) }
updateBoxes(boxes)
This code creates a list of Box objects and updates each one by increasing its value by 1.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each Box object to update its value.
- How many times: Once for each Box in the array, so n times.
Each Box is updated once, so the total work grows directly with the number of Boxes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 updates |
| 100 | 100 updates |
| 1000 | 1000 updates |
Pattern observation: The work increases evenly as the number of Boxes grows.
Time Complexity: O(n)
This means the time to update all Boxes grows in a straight line with the number of Boxes.
[X] Wrong: "Because Boxes share references, updating one Box updates all instantly, so it's constant time."
[OK] Correct: Each Box is a separate object, so each update still happens one by one. Sharing references means changes affect the same object, but you still must visit each object to update it.
Understanding how reference sharing affects operation counts helps you explain side effects clearly. This skill shows you can think about how data changes impact performance in real code.
"What if updateBoxes created new Box objects instead of modifying existing ones? How would the time complexity change?"