Created
January 17, 2019 13:49
-
-
Save charithe/c2a7db6b5102dab622bd19d128406357 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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