Browse Source

cmap: Remove defers (#2210)

All functions in cmap have just one code path. Thus there is not a reason
to use defer statements.
pull/2224/head
Dev Ojha 6 years ago
committed by Anton Kaliaev
parent
commit
d0dcb1cde1
2 changed files with 23 additions and 10 deletions
  1. +12
    -10
      libs/common/cmap.go
  2. +11
    -0
      libs/common/cmap_test.go

+ 12
- 10
libs/common/cmap.go View File

@ -16,58 +16,60 @@ func NewCMap() *CMap {
func (cm *CMap) Set(key string, value interface{}) { func (cm *CMap) Set(key string, value interface{}) {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
cm.m[key] = value cm.m[key] = value
cm.l.Unlock()
} }
func (cm *CMap) Get(key string) interface{} { func (cm *CMap) Get(key string) interface{} {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
return cm.m[key]
val := cm.m[key]
cm.l.Unlock()
return val
} }
func (cm *CMap) Has(key string) bool { func (cm *CMap) Has(key string) bool {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
_, ok := cm.m[key] _, ok := cm.m[key]
cm.l.Unlock()
return ok return ok
} }
func (cm *CMap) Delete(key string) { func (cm *CMap) Delete(key string) {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
delete(cm.m, key) delete(cm.m, key)
cm.l.Unlock()
} }
func (cm *CMap) Size() int { func (cm *CMap) Size() int {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
return len(cm.m)
size := len(cm.m)
cm.l.Unlock()
return size
} }
func (cm *CMap) Clear() { func (cm *CMap) Clear() {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
cm.m = make(map[string]interface{}) cm.m = make(map[string]interface{})
cm.l.Unlock()
} }
func (cm *CMap) Keys() []string { func (cm *CMap) Keys() []string {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
keys := []string{} keys := []string{}
for k := range cm.m { for k := range cm.m {
keys = append(keys, k) keys = append(keys, k)
} }
cm.l.Unlock()
return keys return keys
} }
func (cm *CMap) Values() []interface{} { func (cm *CMap) Values() []interface{} {
cm.l.Lock() cm.l.Lock()
defer cm.l.Unlock()
items := []interface{}{} items := []interface{}{}
for _, v := range cm.m { for _, v := range cm.m {
items = append(items, v) items = append(items, v)
} }
cm.l.Unlock()
return items return items
} }

+ 11
- 0
libs/common/cmap_test.go View File

@ -51,3 +51,14 @@ func TestContains(t *testing.T) {
assert.False(t, cmap.Has("key2")) assert.False(t, cmap.Has("key2"))
assert.Nil(t, cmap.Get("key2")) assert.Nil(t, cmap.Get("key2"))
} }
func BenchmarkCMapHas(b *testing.B) {
m := NewCMap()
for i := 0; i < 1000; i++ {
m.Set(string(i), i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
m.Has(string(i))
}
}

Loading…
Cancel
Save