Sobes.tech
Junior — Middle

Which is faster: a buffered channel or a non-buffered one?

sobes.tech AI

Answer from AI

A buffered channel typically operates faster than a non-buffered channel in situations where the sender can continue working without waiting for the receiver to immediately receive the value. The buffer allows temporarily storing several elements, reducing blocking and synchronization between goroutines.

A non-buffered channel (unbuffered) requires the sender and receiver to synchronize — the sender is blocked until the receiver reads the value, which can slow down execution.

Example:

ch := make(chan int, 10) // buffered channel with size 10

// Sender does not block until the buffer is full
ch <- 1

// Without buffer:
ch2 := make(chan int)
ch2 <- 1 // blocks until someone reads

Thus, buffered channels can improve performance by reducing blocking, but if used improperly, they can lead to data accumulation and increased delays.