Nonisolated methods in Swift - Time & Space Complexity
When we use nonisolated methods in Swift concurrency, we want to know how their execution time changes as the input grows.
We ask: How does the method's work increase when given more data or tasks?
Analyze the time complexity of the following code snippet.
actor DataProcessor {
nonisolated func process(items: [Int]) -> Int {
var sum = 0
for item in items {
sum += item
}
return sum
}
}
This code sums numbers in an array using a nonisolated method inside an actor.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array.
- How many times: Once for every element in the input array.
As the number of items grows, the method does more additions, one per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Nonisolated methods run instantly no matter the input size."
[OK] Correct: Even if nonisolated methods avoid actor isolation, they still do work on each input item, so time grows with input size.
Understanding how nonisolated methods scale helps you explain concurrency choices clearly and shows you grasp how work grows with data.
"What if the method used recursion instead of a loop? How would the time complexity change?"