optimize again

This commit is contained in:
xing 2023-10-28 14:50:06 +08:00
parent f369cf4f22
commit 171b3bc59c

30
cache/map.go vendored
View File

@ -129,25 +129,23 @@ func (m *MapCache[K, V]) GetCache(c context.Context, key K, timeout time.Duratio
} }
func (m *MapCache[K, V]) GetCacheBatch(c context.Context, key []K, timeout time.Duration, params ...any) ([]V, error) { func (m *MapCache[K, V]) GetCacheBatch(c context.Context, key []K, timeout time.Duration, params ...any) ([]V, error) {
var res []V var res = make([]V, 0, len(key))
ver := 0 var ver = 0
var needFlush []K var needFlush []K
var needIndex = make(map[int]K) var needIndex = make(map[K]int)
slice.ForEach(key, func(i int, k K) { for i, k := range key {
v, ok := m.Get(c, k) v, ok := m.Get(c, k)
var vv V if !ok {
if ok {
vv = v
} else {
needFlush = append(needFlush, k) needFlush = append(needFlush, k)
ver += m.Ver(c, k) ver += m.Ver(c, k)
needIndex[i] = k needIndex[k] = i
}
res = append(res, v)
} }
res = append(res, vv)
})
if len(needFlush) < 1 { if len(needFlush) < 1 {
return res, nil return res, nil
} }
var err error var err error
call := func() { call := func() {
m.mux.Lock() m.mux.Lock()
@ -168,6 +166,9 @@ func (m *MapCache[K, V]) GetCacheBatch(c context.Context, key []K, timeout time.
} }
for k, v := range r { for k, v := range r {
m.Set(c, k, v) m.Set(c, k, v)
if i, ok := needIndex[k]; ok {
res[i] = v
}
} }
} }
if timeout > 0 { if timeout > 0 {
@ -186,11 +187,6 @@ func (m *MapCache[K, V]) GetCacheBatch(c context.Context, key []K, timeout time.
} else { } else {
call() call()
} }
for index, k := range needIndex {
v, ok := m.Get(c, k)
if ok {
res[index] = v
}
}
return res, err return res, err
} }