0
0
Swiftprogramming~5 mins

Reference sharing and side effects in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Reference sharing and side effects
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each Box is updated once, so the total work grows directly with the number of Boxes.

Input Size (n)Approx. Operations
1010 updates
100100 updates
10001000 updates

Pattern observation: The work increases evenly as the number of Boxes grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to update all Boxes grows in a straight line with the number of Boxes.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if updateBoxes created new Box objects instead of modifying existing ones? How would the time complexity change?"