Skip to content

Instantly share code, notes, and snippets.

@DeanThompson
Created December 18, 2014 07:19
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 DeanThompson/48365dc9472e0a64dba1 to your computer and use it in GitHub Desktop.
Save DeanThompson/48365dc9472e0a64dba1 to your computer and use it in GitHub Desktop.
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