Sending and receiving values in Go - Time & Space 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?
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 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.
As the number of values to send and receive grows, the total operations grow in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 sends + 10 receives = 20 |
| 100 | 100 sends + 100 receives = 200 |
| 1000 | 1000 sends + 1000 receives = 2000 |
Pattern observation: The total work grows directly with the number of values sent and received.
Time Complexity: O(n)
This means the time to send and receive values grows in a straight line as the number of values increases.
[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.
Understanding how sending and receiving values scale helps you reason about concurrent programs and their performance in real projects.
"What if we used buffered channels with capacity n? How would the time complexity change?"