Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmark Mutex vs Channel
package main
import (
"errors"
"sync"
"testing"
)
func BenchmarkChannel(b *testing.B) {
ch := make(chan error, 1)
for i := 0; i < b.N; i++ {
wg := sync.WaitGroup{}
wg.Add(16)
err := errors.New("unknown error")
for i := 0; i < 16; i++ {
go func() {
defer wg.Done()
select {
case ch <- err:
default:
}
}()
}
wg.Wait()
}
}
func BenchmarkMutex(b *testing.B) {
var firstError error
var mutex sync.Mutex
for i := 0; i < b.N; i++ {
wg := sync.WaitGroup{}
wg.Add(16)
err := errors.New("unknown error")
for i := 0; i < 16; i++ {
go func() {
defer wg.Done()
mutex.Lock()
defer mutex.Unlock()
if firstError == nil {
firstError = err
}
}()
}
wg.Wait()
}
}
@draveness
Copy link
Author

draveness commented Jul 11, 2019

$ go test -benchmem -bench .
goos: darwin
goarch: amd64
pkg: github.com/golang/playground
BenchmarkChannel-8   	  300000	      4525 ns/op	      32 B/op	       2 allocs/op
BenchmarkMutex-8     	  200000	      6342 ns/op	      32 B/op	       2 allocs/op
PASS
ok  	github.com/golang/playground	2.749s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment