Skip to content

Instantly share code, notes, and snippets.

@charithe
Created January 17, 2019 13:49
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 charithe/c2a7db6b5102dab622bd19d128406357 to your computer and use it in GitHub Desktop.
Save charithe/c2a7db6b5102dab622bd19d128406357 to your computer and use it in GitHub Desktop.
package mapbench
import (
"sync"
log "github.com/sirupsen/logrus"
)
type MapBench struct {
objects sync.Map
logger *log.Logger
}
func (m *MapBench) CreateIfNotLoaded(key string) *Obj {
v, ok := m.objects.Load(key)
if !ok {
newObj := &Obj{
logger: m.logger.WithField("key", key),
}
v, _ = m.objects.LoadOrStore(key, newObj)
}
return v.(*Obj)
}
func (m *MapBench) CreateAlways(key string) *Obj {
newObj := &Obj{
logger: m.logger.WithField("key", key),
}
v, _ := m.objects.LoadOrStore(key, newObj)
return v.(*Obj)
}
type MapKey struct {
somechan chan string
}
type Obj struct {
somechan chan string
mu sync.RWMutex
somemap map[*MapKey]struct{}
logger *log.Entry
}
func (o *Obj) DoSomething() {
o.logger.Debug("x")
}
package mapbench
import (
"fmt"
"testing"
log "github.com/sirupsen/logrus"
)
func BenchmarkSyncMap(b *testing.B) {
numKeys := 100
keys := make([]string, numKeys)
for i := 0; i < numKeys; i++ {
keys[i] = fmt.Sprintf("key%d", i)
}
b.Run("CreateIfNotLoaded", func(b *testing.B) {
b.ReportAllocs()
mb := &MapBench{
logger: log.New(),
}
for i := 0; i < b.N; i++ {
o := mb.CreateIfNotLoaded(keys[i%numKeys])
o.DoSomething()
}
})
b.Run("CreateAlways", func(b *testing.B) {
b.ReportAllocs()
mb := &MapBench{
logger: log.New(),
}
for i := 0; i < b.N; i++ {
o := mb.CreateAlways(keys[i%numKeys])
o.DoSomething()
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment