Actors vs locks decision in Swift - Performance Comparison
When deciding between actors and locks in Swift concurrency, it's important to understand how the time cost grows as your program handles more tasks or data.
We want to see how the choice affects the speed of code when many operations happen.
Analyze the time complexity of this simple counter using locks.
class CounterWithLock {
private var value = 0
private let lock = NSLock()
func increment() {
lock.lock()
value += 1
lock.unlock()
}
func getValue() -> Int {
lock.lock()
defer { lock.unlock() }
return value
}
}
This code uses a lock to protect a shared counter from multiple threads changing it at the same time.
Look at what repeats when many increments happen.
- Primary operation: Locking and unlocking around increment.
- How many times: Once per increment call, repeated for each increment.
Each increment requires locking and unlocking, so the time grows with the number of increments.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lock/unlock + increments |
| 100 | 100 lock/unlock + increments |
| 1000 | 1000 lock/unlock + increments |
Pattern observation: Time grows directly with the number of increments because each needs a lock.
Time Complexity: O(n)
This means the time to complete all increments grows in a straight line as you add more increments.
[X] Wrong: "Using locks or actors makes the code run in the same time regardless of how many increments happen."
[OK] Correct: Each increment still needs to wait for the lock or actor to be ready, so more increments mean more total time.
Understanding how locking or actors affect time helps you explain your choices clearly and shows you know how concurrency impacts performance.
What if we replaced the lock with an actor to manage the counter? How would the time complexity change?