go 里的 syncLock 和 channel 的性能有区别吗?

参考解析

题目来源: 小米

答案:

channel的底层也是用了syns.Mutex,算是对锁的封装,性能应该是有损耗的,用测试的数据更有说服力

  1. package channel
  2. import "sync"
  3. var mutex = sync.Mutex{}
  4. var ch = make(chan struct{}, 1)
  5. func UseMutex() {
  6. mutex.Lock()
  7. mutex.Unlock()
  8. }
  9. func UseChan() {
  10. ch <- struct{}{}
  11. <-ch
  12. }
  1. package channel
  2. import "testing"
  3. func BenchmarkUseMutex(b *testing.B) {
  4. for i := 0; i < b.N; i++ {
  5. UseMutex()
  6. }
  7. }
  8. func BenchmarkUseChan(b *testing.B) {
  9. for i := 0; i < b.N; i++ {
  10. UseChan()
  11. }
  12. }

执行bench命令

  1. go test -bench=.

测试结果如下

  1. BenchmarkUseMutex-8 87120927 13.61 ns/op
  2. BenchmarkUseChan-8 42295345 26.47 ns/op
  3. PASS
  4. ok mytest/channel 2.906s

根据压测结果来说Mutex 比 channel的性能快了两倍左右