Skip to content

Commit

Permalink
avoid heap alloc on every req; use b2s
Browse files Browse the repository at this point in the history
  • Loading branch information
thehowl committed Dec 13, 2017
1 parent cd8450d commit 0e77ecf
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ package fasthttprouter

import (
"strings"
"unsafe"

"github.com/erikdubbelboer/fasthttp"
)
Expand Down Expand Up @@ -293,8 +294,8 @@ func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
defer r.recv(ctx)
}

path := string(ctx.Path())
method := string(ctx.Method())
path := b2s(ctx.Path())
method := b2s(ctx.Method())
if root := r.trees[method]; root != nil {
if f, tsr := root.getValue(path, ctx); f != nil {
f(ctx)
Expand Down Expand Up @@ -377,3 +378,12 @@ func (r *Router) Handler(ctx *fasthttp.RequestCtx) {
fasthttp.StatusNotFound)
}
}

// b2s converts byte slice to a string without memory allocation.
// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .
//
// Note it may break if string and/or slice header will change
// in the future go versions.
func b2s(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

0 comments on commit 0e77ecf

Please sign in to comment.