improved query cache

This commit is contained in:
ston1th 2018-01-17 23:00:55 +01:00
commit 228fe95519

View file

@ -7,20 +7,26 @@ import (
"sync"
)
// DefaultCacheSize is the default cache size
const DefaultCacheSize = 100
// QueryCache can be used to cache queries
type QueryCache struct {
// protects m
sync.RWMutex
m map[string]Query
max int
m map[string]*Query
size int
}
// NewQueryCache returns a new QueryCache
func NewQueryCache(max int) *QueryCache {
func NewQueryCache(size int) *QueryCache {
if size <= 0 {
size = DefaultCacheSize
}
return &QueryCache{
m: make(map[string]Query),
max: max,
m: make(map[string]*Query),
size: size,
}
}
@ -37,10 +43,10 @@ func (qc *QueryCache) NewQuery(s string) (q *Query, err error) {
}
qc.Lock()
defer qc.Unlock()
if len(qc.m) == qc.max {
if len(qc.m) == qc.size {
qc.clean()
}
qc.m[s] = *q
qc.m[s] = q
return
}
@ -49,7 +55,7 @@ func (qc *QueryCache) Lookup(s string) *Query {
qc.RLock()
defer qc.RUnlock()
if q, ok := qc.m[s]; ok {
return &q
return q
}
return nil
}