defer性能测试数据大概相差4-5倍的样子,测试环境 go 1.8
package test import ( "sync" "testing" ) var m sync.Mutex func call() { m.Lock() m.Unlock() } func deferCall() { m.Lock() defer m.Unlock() } func BenchmarkCall(b *testing.B) { for i := 0; i < b.N; i++ { call() } } func BenchmarkDeferCall(b *testing.B) { for i := 0; i < b.N; i++ { deferCall() } } /* BenchmarkCall-8 100000000 22.2 ns/op BenchmarkDeferCall-8 10000000 118 ns/op PASS ok defer_perf 3.557s */
github gists 需要翻墙 gitst