0
0
Swiftprogramming~5 mins

Distributed actors overview in Swift - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Distributed actors overview
O(n)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling sendMessage on the distributed actor for each message.
  • How many times: Once for every message in the messages array.
How Execution Grows With Input

Each message requires a separate remote call, so the total work grows as the number of messages increases.

Input Size (n)Approx. Operations
1010 remote calls
100100 remote calls
10001000 remote calls

Pattern observation: The work grows directly with the number of messages; doubling messages doubles calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to send messages grows in a straight line with how many messages you send.

Common Mistake

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

Interview Connect

Understanding how remote calls add up helps you design better distributed systems and shows you can think about performance beyond local code.

Self-Check

What if we sent all messages in parallel instead of waiting for each one? How would the time complexity change?