1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 18:17:52 -05:00

optimize CachedMatcherGroup

This commit is contained in:
Darien Raymond 2018-08-19 22:16:06 +02:00
parent e72d4d6c25
commit 26f52e61db
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
2 changed files with 23 additions and 7 deletions

View File

@ -34,3 +34,20 @@ func BenchmarkMarchGroup(b *testing.B) {
_ = g.Match("0.v2ray.com") _ = g.Match("0.v2ray.com")
} }
} }
func BenchmarkCachedMarchGroup(b *testing.B) {
g := NewMatcherGroup()
for i := 1; i <= 1024; i++ {
m, err := Domain.New(strconv.Itoa(i) + ".v2ray.com")
common.Must(err)
g.Add(m)
}
cg := NewCachedMatcherGroup(g)
_ = cg.Match("0.v2ray.com")
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = cg.Match("0.v2ray.com")
}
}

View File

@ -112,7 +112,7 @@ type cacheEntry struct {
} }
type CachedMatcherGroup struct { type CachedMatcherGroup struct {
sync.Mutex sync.RWMutex
group *MatcherGroup group *MatcherGroup
cache map[string]cacheEntry cache map[string]cacheEntry
cleanup *task.Periodic cleanup *task.Periodic
@ -129,7 +129,7 @@ func NewCachedMatcherGroup(g *MatcherGroup) *CachedMatcherGroup {
r.Lock() r.Lock()
defer r.Unlock() defer r.Unlock()
expire := time.Now().Add(-1 * time.Second * 60) expire := time.Now().Add(-1 * time.Second * 120)
for p, e := range r.cache { for p, e := range r.cache {
if e.timestamp.Before(expire) { if e.timestamp.Before(expire) {
delete(r.cache, p) delete(r.cache, p)
@ -143,22 +143,21 @@ func NewCachedMatcherGroup(g *MatcherGroup) *CachedMatcherGroup {
} }
func (g *CachedMatcherGroup) Match(pattern string) uint32 { func (g *CachedMatcherGroup) Match(pattern string) uint32 {
g.Lock() g.RLock()
defer g.Unlock()
r, f := g.cache[pattern] r, f := g.cache[pattern]
g.RUnlock()
if f { if f {
r.timestamp = time.Now()
g.cache[pattern] = r
return r.result return r.result
} }
mr := g.group.Match(pattern) mr := g.group.Match(pattern)
g.Lock()
g.cache[pattern] = cacheEntry{ g.cache[pattern] = cacheEntry{
result: mr, result: mr,
timestamp: time.Now(), timestamp: time.Now(),
} }
g.Unlock()
return mr return mr
} }