Skip to content

Commit

Permalink
triemux: make shouldRedirToLowercase more efficient by regex compilat…
Browse files Browse the repository at this point in the history
…ion+reuse

This change makes shouldRedirToLowercase more efficient by
at start-up time compiling the regular expression that
shouldRedirToLowercase uses instead of compiling and
discarding it each time on a hit, with an exhibit below
of the performance improvement:

```shell
$ benchstat before.txt after.txt
name                             old time/op    new time/op    delta
ShouldRedirectToLowercasePath-8    29.8µs ± 1%     0.8µs ±24%   -97.15%  (p=0.000 n=8+10)

name                             old alloc/op   new alloc/op   delta
ShouldRedirectToLowercasePath-8    33.7kB ± 0%     0.0kB       -100.00%  (p=0.000 n=9+10)

name                             old allocs/op  new allocs/op  delta
ShouldRedirectToLowercasePath-8       360 ± 0%         0       -100.00%  (p=0.000 n=10+10)
```

Fixes #444
  • Loading branch information
odeke-em committed Apr 3, 2024
1 parent 919496a commit 1b6c75e
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions triemux/mux.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,15 +59,16 @@ func (mux *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
handler.ServeHTTP(w, r)
}

var reShouldRedirect = regexp.MustCompile(`^\/[A-Z]+[A-Z\W\d]+$`)

// shouldRedirToLowercasePath takes a URL path string (such as "/government/guidance")
// and returns:
// - true, if path is in all caps; for example:
// "/GOVERNMENT/GUIDANCE" -> true (should redirect to "/government/guidance")
// - false, otherwise; for example:
// "/GoVeRnMeNt/gUiDaNcE" -> false (should forward "/GoVeRnMeNt/gUiDaNcE" as-is)
func shouldRedirToLowercasePath(path string) (match bool) {
match, _ = regexp.MatchString(`^\/[A-Z]+[A-Z\W\d]+$`, path)
return
return reShouldRedirect.MatchString(path)
}

// lookup finds a URL path in the Mux and returns the corresponding handler.
Expand Down

0 comments on commit 1b6c75e

Please sign in to comment.