Built-in property wrappers (@State, @Published) in Swift - Time & Space Complexity
When using built-in property wrappers like @State and @Published, it's important to understand how their updates affect program speed.
We want to know how the time to update or notify changes grows as the number of properties or observers increases.
Analyze the time complexity of updating a @Published property with multiple observers.
class Model: ObservableObject {
@Published var value: Int = 0
}
let model = Model()
// Simulate multiple observers
for _ in 1...n {
model.$value.sink { newValue in
print("Value changed to \(newValue)")
}
}
model.value = 10
This code sets up a @Published property and attaches n observers that react when the value changes.
Look for repeated actions that affect performance.
- Primary operation: Notifying each observer when the property changes.
- How many times: Once per observer, so n times for n observers.
As the number of observers (n) increases, the time to notify all observers grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 notifications |
| 100 | 100 notifications |
| 1000 | 1000 notifications |
Pattern observation: Doubling the number of observers doubles the notification work.
Time Complexity: O(n)
This means notifying observers takes time proportional to how many observers there are.
[X] Wrong: "Updating a @Published property is always fast and constant time regardless of observers."
[OK] Correct: Each observer must be notified, so more observers mean more work and longer update time.
Understanding how property wrappers notify observers helps you reason about app responsiveness and performance in real projects.
What if we changed from multiple observers to a single observer that updates multiple UI elements internally? How would the time complexity change?