Closed
Description
Currently, LoadOrStore
only allows passing a value directly, however, considering this case:
var smap sync.Map
// creating value needs a factory function
// maybe a heavy overhead initialization function
// always initialized even there has been an object loaded from the below map
bar := NewValue()
smap.LoadOrStore("foo", bar)
if I want to avoid this initialization every time, I have to give up using LoadOrStore
or combine it and sync.Pool
: implement the lazy initialization when there is not an existing value be loaded:
var smap sync.Map
bar := valuePool.Get().(*Bar)
bar, loaded := smap.LoadOrStore("foo", bar)
if !loaded {
bar.Init()
} else {
valuePool.Put(bar)
}
if there is a way to put a New
closure into LoadOrStore
function, maybe like:
func (m *Map) LoadOrStoreFrom(key interface{}, newValue func() interface{}) (actual interface{}, loaded bool)
it may reduce tons of overhead in this case, and I think the above case is common to meet.