0
0
Goprogramming~5 mins

Channel closing behavior in Go - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Channel closing behavior
O(n)
Understanding Time Complexity

When working with channels in Go, it's important to understand how closing a channel affects the program's speed.

We want to see how the time to close and read from a channel changes as the number of messages grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


ch := make(chan int, n)
for i := 0; i < n; i++ {
    ch <- i
}
close(ch)
for v := range ch {
    _ = v
}
    

This code fills a channel with n integers, closes it, then reads all values until the channel is empty.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Sending and receiving values in a loop over n items.
  • How many times: Each loop runs n times, once for each item.
How Execution Grows With Input

As the number of items n increases, the total operations increase proportionally.

Input Size (n)Approx. Operations
10About 20 (10 sends + 10 receives)
100About 200 (100 sends + 100 receives)
1000About 2000 (1000 sends + 1000 receives)

Pattern observation: The work grows linearly with the number of items sent and received.

Final Time Complexity

Time Complexity: O(n)

This means the time to send, close, and receive all items grows directly with the number of items.

Common Mistake

[X] Wrong: "Closing a channel instantly empties it, so reading after close is free."

[OK] Correct: Even after closing, you must receive each item one by one, so reading still takes time proportional to the number of items.

Interview Connect

Understanding how channel operations scale helps you write efficient concurrent programs and explain your reasoning clearly in interviews.

Self-Check

"What if we replaced the buffered channel with an unbuffered channel? How would the time complexity change?"