From 228fe955194f460d6bba01894498073601a5d7b3 Mon Sep 17 00:00:00 2001 From: ston1th Date: Wed, 17 Jan 2018 23:00:55 +0100 Subject: [PATCH] improved query cache --- cache.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/cache.go b/cache.go index 9ff2fb8..2b7508b 100644 --- a/cache.go +++ b/cache.go @@ -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 }