-
Notifications
You must be signed in to change notification settings - Fork 19
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Local counter: Don't re-allocate maps in Go 1.21+
- Loading branch information
1 parent
05a79e9
commit 116024c
Showing
3 changed files
with
46 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
//go:build !go1.21 | ||
|
||
package httprate | ||
|
||
import "time" | ||
|
||
func (c *localCounter) evict(currentWindow time.Time) { | ||
if c.latestWindow == currentWindow { | ||
return | ||
} | ||
|
||
previousWindow := currentWindow.Add(-c.windowLength) | ||
if c.latestWindow == previousWindow { | ||
c.latestWindow = currentWindow | ||
c.latestCounters, c.previousCounters = make(map[uint64]int), c.latestCounters | ||
return | ||
} | ||
|
||
c.latestWindow = currentWindow | ||
c.previousCounters, c.latestCounters = make(map[uint64]int), make(map[uint64]int) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
//go:build go1.21 | ||
|
||
package httprate | ||
|
||
import "time" | ||
|
||
func (c *localCounter) evict(currentWindow time.Time) { | ||
if c.latestWindow == currentWindow { | ||
return | ||
} | ||
|
||
previousWindow := currentWindow.Add(-c.windowLength) | ||
if c.latestWindow == previousWindow { | ||
c.latestWindow = currentWindow | ||
// Shift the windows without map re-allocation. | ||
clear(c.previousCounters) | ||
c.latestCounters, c.previousCounters = c.previousCounters, c.latestCounters | ||
return | ||
} | ||
|
||
c.latestWindow = currentWindow | ||
|
||
clear(c.previousCounters) | ||
clear(c.latestCounters) | ||
} |