我在Go中使用互斥锁进行同步。下面是代码
func (c *MyStruct) Put(key string, value interface{}) {
c.mu.Lock()
defer c.mu.Unlock()
val, found := c.items[key]
if found {
item := val.Value.(*Item)
item.Value = value
item.Expiration = time.Now().Add(c.ttl).UnixNano()
return
}
ele := c.list.PushFront(&Item{key, value, expirationTime})
c.items[key] = ele
}
当我对此进行基准测试时,输出似乎是
BenchmarkXxx-12 5000000 206 ns/op 37 B/op 2 allocs/op
但是当我更改代码并在功能结束时手动解锁互斥锁时。它正在提高性能。
BenchmarkLru_put-12 10000000 157 ns/op 26 B/op 2 allocs/op
延迟功能会增加代码延迟吗?在这种情况下,我需要避免使用defer吗?