Last active
July 27, 2020 11:18
-
-
Save vitalyisaev2/5791627ffc48f10c2fde22c2a5dd32ee to your computer and use it in GitHub Desktop.
Golang buffered channel vs blocking channel performance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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