Skip to content

Optimize throttle middleware by avoiding unnecessary timer creation #1011

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

vasayxtx
Copy link
Contributor

@vasayxtx vasayxtx commented Aug 1, 2025

  • Only create time.NewTimer() when actually needed to wait
  • Reduces allocations from 7 to 4 and memory usage by ~54%
  • Improves performance by ~50% in high-throughput scenarios

Benchmark results:

Before:

goos: darwin
goarch: arm64
pkg: github.com/go-chi/chi/v5/middleware
cpu: Apple M1 Max
BenchmarkThrottle
BenchmarkThrottle-10    	 3349486	       382.3 ns/op	     456 B/op	       7 allocs/op
PASS

After:

goos: darwin
goarch: arm64
pkg: github.com/go-chi/chi/v5/middleware
cpu: Apple M1 Max
BenchmarkThrottle
BenchmarkThrottle-10    	 6310284	       186.9 ns/op	     208 B/op	       4 allocs/op
PASS

- Only create time.NewTimer() when actually needed to wait
- Reduces allocations from 7 to 4 and memory usage by ~54%
- Improves performance by ~50% in high-throughput scenarios
Copy link
Contributor

@VojtechVitek VojtechVitek left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thank you!

I'll wait few more days before merging to allow more 👀 reviews

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants