Skip to content

Instantly share code, notes, and snippets.

@vitalyisaev2
Last active July 27, 2020 11:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vitalyisaev2/5791627ffc48f10c2fde22c2a5dd32ee to your computer and use it in GitHub Desktop.
Save vitalyisaev2/5791627ffc48f10c2fde22c2a5dd32ee to your computer and use it in GitHub Desktop.
Golang buffered channel vs blocking channel performance
/*
BenchmarkBufferedChannel-4 5000 267997 ns/op
BenchmarkBlockingChannel-4 3000 388019 ns/op
*/
package performance_test
import (
"math/rand"
"testing"
)
const (
size = 1024
)
var (
values []int
)
func init() {
values = make([]int, size)
for i := range values {
values[i] = rand.Int()
}
}
func bufferedChannel() {
intChannel := make(chan int, size)
for i := 0; i < size; i++ {
go func(j int) {
intChannel <- values[j]
}(i)
}
for k := 0; k < size; k++ {
_ = <-intChannel
}
}
func blockingChannel() {
intChannel := make(chan int)
for i := 0; i < size; i++ {
go func(j int) {
intChannel <- values[j]
}(i)
}
for k := 0; k < size; k++ {
_ = <-intChannel
}
}
func BenchmarkBufferedChannel(b *testing.B) {
for n := 0; n < b.N; n++ {
bufferedChannel()
}
}
func BenchmarkBlockingChannel(b *testing.B) {
for n := 0; n < b.N; n++ {
blockingChannel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment