perf: in-place filtering in RateLimiter to reduce GC pressure
This commit is contained in:
@@ -63,14 +63,15 @@ func (rl *RateLimiter) Allow(key string) bool {
|
|||||||
sw.mu.Lock()
|
sw.mu.Lock()
|
||||||
defer sw.mu.Unlock()
|
defer sw.mu.Unlock()
|
||||||
|
|
||||||
// Remove expired tokens
|
// Remove expired tokens using in-place filtering to avoid GC pressure.
|
||||||
var valid []time.Time
|
n := 0
|
||||||
for _, t := range sw.tokens {
|
for _, t := range sw.tokens {
|
||||||
if t.After(cutoff) {
|
if t.After(cutoff) {
|
||||||
valid = append(valid, t)
|
sw.tokens[n] = t
|
||||||
|
n++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
sw.tokens = valid
|
sw.tokens = sw.tokens[:n]
|
||||||
|
|
||||||
if len(sw.tokens) >= rl.limit {
|
if len(sw.tokens) >= rl.limit {
|
||||||
return false
|
return false
|
||||||
|
|||||||
Reference in New Issue
Block a user