Channel closing behavior in Go - Time & Space 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.
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 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.
As the number of items n increases, the total operations increase proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 sends + 10 receives) |
| 100 | About 200 (100 sends + 100 receives) |
| 1000 | About 2000 (1000 sends + 1000 receives) |
Pattern observation: The work grows linearly with the number of items sent and received.
Time Complexity: O(n)
This means the time to send, close, and receive all items grows directly with the number of items.
[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.
Understanding how channel operations scale helps you write efficient concurrent programs and explain your reasoning clearly in interviews.
"What if we replaced the buffered channel with an unbuffered channel? How would the time complexity change?"