Buffered and unbuffered channels in Go - Time & Space Complexity
When using channels in Go, it's important to understand how sending and receiving messages affects program speed.
We want to see how the time to send and receive changes as we increase the number of messages.
Analyze the time complexity of sending messages through buffered and unbuffered channels.
package main
func main() {
ch := make(chan int, 3) // buffered channel with capacity 3
for i := 0; i < 5; i++ {
ch <- i // send value to channel
}
}
This code sends 5 integers into a buffered channel that can hold 3 items before blocking.
Look at what repeats as the program runs.
- Primary operation: Sending values into the channel inside the loop.
- How many times: 5 times, once per loop iteration.
As the number of messages to send increases, the time to send grows depending on channel type.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 sends; some may block if unbuffered |
| 100 | About 100 sends; blocking happens often if unbuffered |
| 1000 | About 1000 sends; blocking dominates if unbuffered |
Pattern observation: Each send is done once, but blocking can add waiting time especially for unbuffered channels.
Time Complexity: O(n)
This means the time to send n messages grows roughly in direct proportion to n.
[X] Wrong: "Buffered channels always make sending instant and constant time."
[OK] Correct: Buffered channels only delay blocking until the buffer is full; after that, sending still waits, so time grows with messages.
Understanding how channels behave with different buffering helps you reason about program speed and concurrency, a useful skill in many coding challenges.
"What if we changed the buffered channel size to be equal to the number of messages? How would the time complexity change?"