Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A simple test case to measure the additional time taken by defer in golang
package test
import (
"sync"
"testing"
)
type SyncedStruct struct {
a int
mutex sync.RWMutex
}
var (
item = SyncedStruct{a: 1}
)
func DeferredUnlock() {
item.mutex.Lock()
defer item.mutex.Unlock()
_ = item.a
}
func NotDeferredUnlock() {
item.mutex.Lock()
_ = item.a
item.mutex.Unlock()
}
func BenchmarkDeferredUnlock(t *testing.B) {
for i := 0; i < t.N; i++ {
DeferredUnlock()
}
}
func BenchmarkNotDeferredUnlock(t *testing.B) {
for i := 0; i < t.N; i++ {
NotDeferredUnlock()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment