0
0
Goprogramming~5 mins

Sending and receiving values in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Sending and receiving values
O(n)
Understanding Time Complexity

When we send and receive values in Go channels, we want to know how the time to do this changes as we handle more data.

We ask: How does the number of send and receive actions grow with the input size?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

package main

func main() {
  ch := make(chan int)

  go func() {
    for i := 0; i < 5; i++ {
      ch <- i
    }
    close(ch)
  }()

  for val := range ch {
    _ = val
  }
}

This code sends 5 values into a channel and receives them in the main goroutine.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Sending and receiving values in a loop.
  • How many times: 5 times each for sending and receiving.
How Execution Grows With Input

As the number of values to send and receive grows, the total operations grow in the same way.

Input Size (n)Approx. Operations
1010 sends + 10 receives = 20
100100 sends + 100 receives = 200
10001000 sends + 1000 receives = 2000

Pattern observation: The total work grows directly with the number of values sent and received.

Final Time Complexity

Time Complexity: O(n)

This means the time to send and receive values grows in a straight line as the number of values increases.

Common Mistake

[X] Wrong: "Sending and receiving values in channels is constant time no matter how many values there are."

[OK] Correct: Each value must be sent and received separately, so the total time grows with the number of values.

Interview Connect

Understanding how sending and receiving values scale helps you reason about concurrent programs and their performance in real projects.

Self-Check

"What if we used buffered channels with capacity n? How would the time complexity change?"