Skip to content

Commit 6aa26b0

Browse files
authored
Local counter: Don't re-allocate maps in Go 1.21+ (#40)
1 parent 9e50ad6 commit 6aa26b0

File tree

3 files changed

+46
-17
lines changed

3 files changed

+46
-17
lines changed

local_counter.go

-17
Original file line numberDiff line numberDiff line change
@@ -68,23 +68,6 @@ func (c *localCounter) Increment(key string, currentWindow time.Time) error {
6868
return c.IncrementBy(key, currentWindow, 1)
6969
}
7070

71-
func (c *localCounter) evict(currentWindow time.Time) {
72-
if c.latestWindow == currentWindow {
73-
return
74-
}
75-
76-
previousWindow := currentWindow.Add(-c.windowLength)
77-
if c.latestWindow == previousWindow {
78-
c.latestWindow = currentWindow
79-
c.latestCounters, c.previousCounters = make(map[uint64]int), c.latestCounters
80-
return
81-
}
82-
83-
c.latestWindow = currentWindow
84-
// NOTE: Don't use clear() to be compatible with older version of Go.
85-
c.previousCounters, c.latestCounters = make(map[uint64]int), make(map[uint64]int)
86-
}
87-
8871
func limitCounterKey(key string) uint64 {
8972
h := xxhash.New()
9073
h.WriteString(key)

local_counter_go1.20.go

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//go:build !go1.21
2+
3+
package httprate
4+
5+
import "time"
6+
7+
func (c *localCounter) evict(currentWindow time.Time) {
8+
if c.latestWindow == currentWindow {
9+
return
10+
}
11+
12+
previousWindow := currentWindow.Add(-c.windowLength)
13+
if c.latestWindow == previousWindow {
14+
c.latestWindow = currentWindow
15+
c.latestCounters, c.previousCounters = make(map[uint64]int), c.latestCounters
16+
return
17+
}
18+
19+
c.latestWindow = currentWindow
20+
c.previousCounters, c.latestCounters = make(map[uint64]int), make(map[uint64]int)
21+
}

local_counter_go1.21.go

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
//go:build go1.21
2+
3+
package httprate
4+
5+
import "time"
6+
7+
func (c *localCounter) evict(currentWindow time.Time) {
8+
if c.latestWindow == currentWindow {
9+
return
10+
}
11+
12+
previousWindow := currentWindow.Add(-c.windowLength)
13+
if c.latestWindow == previousWindow {
14+
c.latestWindow = currentWindow
15+
// Shift the windows without map re-allocation.
16+
clear(c.previousCounters)
17+
c.latestCounters, c.previousCounters = c.previousCounters, c.latestCounters
18+
return
19+
}
20+
21+
c.latestWindow = currentWindow
22+
23+
clear(c.previousCounters)
24+
clear(c.latestCounters)
25+
}

0 commit comments

Comments
 (0)