Skip to content

Instantly share code, notes, and snippets.

@draveness
Created July 11, 2019 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draveness/f97a12296bd7b19a6c22e45daaee3930 to your computer and use it in GitHub Desktop.
Save draveness/f97a12296bd7b19a6c22e45daaee3930 to your computer and use it in GitHub Desktop.
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

$ 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