Distributed actors overview in Swift - Time & Space Complexity
When working with distributed actors in Swift, it's important to understand how the time to complete tasks changes as the number of remote calls grows.
We want to know how the program's work increases when it talks to more actors over the network.
Analyze the time complexity of the following code snippet.
distributed actor ChatRoom {
distributed func sendMessage(_ message: String) async {
// send message to all participants
}
}
func broadcastMessages(room: ChatRoom, messages: [String]) async {
for msg in messages {
await room.sendMessage(msg)
}
}
This code sends multiple messages to a distributed actor, one after another, waiting for each to finish.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling
sendMessageon the distributed actor for each message. - How many times: Once for every message in the
messagesarray.
Each message requires a separate remote call, so the total work grows as the number of messages increases.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 remote calls |
| 100 | 100 remote calls |
| 1000 | 1000 remote calls |
Pattern observation: The work grows directly with the number of messages; doubling messages doubles calls.
Time Complexity: O(n)
This means the time to send messages grows in a straight line with how many messages you send.
[X] Wrong: "Calling a distributed actor method is instant and does not add time."
[OK] Correct: Each call involves network communication, which takes time and adds up when repeated many times.
Understanding how remote calls add up helps you design better distributed systems and shows you can think about performance beyond local code.
What if we sent all messages in parallel instead of waiting for each one? How would the time complexity change?