Junior — Middle
In what situation does data transfer through a buffered goroutine happen faster than through an unbuffered one?
sobes.tech AI
Answer from AI
Sending data through a buffered goroutine (channel with buffer) is faster than through an unbuffered one when the sender can write data into the channel buffer and continue working without waiting for the receiver to read the data.
In an unbuffered channel, the sender blocks until the receiver reads the data, which can slow down execution if the receiver is busy.
Example situation:
- The sender generates data faster than the receiver processes it.
- The channel buffer allows accumulating several messages, reducing blocking and increasing throughput.
ch := make(chan int, 5) // buffered channel with size 5
// Sender
for i := 0; i < 10; i++ {
ch <- i // does not block until buffer is full
}
// Receiver
for i := 0; i < 10; i++ {
fmt.Println(<-ch)
}
Thus, buffering helps smooth out the speed difference between sender and receiver.