golang defer has an associated performance cost
golang defer keyword doesn't come free. Let's see this in action
main_test.go
package main
import (
"sync"
"testing"
)
func withoutDefer() {
mu.Lock()
// critical section
mu.Unlock()
}
func withDefer() {
mu.Lock()
defer mu.Unlock()
// critical section
}
var mu sync.Mutex
func BenchmarkWithoutDefer(b *testing.B) {
for i := 0; i < b.N; i++ {
withoutDefer()
}
}
func BenchmarkWithDefer(b *testing.B) {
for i := 0; i < b.N; i++ {
withDefer()
}
}
Run the following command
go test -bench=.
Performance results shows that it can be slower as shown here
Comments