Skip to content
Myr

chore(performance): improve countParams (#2378)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* update Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com> * chore: update * chore: improve countParams performance * update Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com> * chore: add comment

authored by Bo-Yi Wu · committed by GitHub · parent 1d5b9ba · Browse files · 1 file+37 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+37 added−8 removed

  • other:+37 added−8 removed

1 file+37 added−8 removed

modified:tree.go+37 added-8 removed
3 unmodified lines
45package gin67import (8 "bytes"9 "net/url"10 "reflect"11 "strings"12 "unicode"13 "unicode/utf8"14 "unsafe"15)1617var (18 strColon = []byte(":")19 strStar = []byte("*")20)2122// Param is a single URL parameter, consisting of a key and a value.23type Param struct {24 Key string25 Value string
53 unmodified lines
79 }80 return i81}8283// bytesToStr converts byte slice to a string without memory allocation.84// See https://groups.google.com/forum/#!msg/Golang-Nuts/ENgbUzYvCuU/90yGx7GUAgAJ .85//86// Note it may break if string and/or slice header will change87// in the future go versions.88func bytesToStr(b []byte) string {89 return *(*string)(unsafe.Pointer(&b))90}9192// strToBytes converts string to a byte slice without memory allocation.93//94// Note it may break if string and/or slice header will change95// in the future go versions.96func strToBytes(s string) (b []byte) {97 /* #nosec G103 */98 bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))99 /* #nosec G103 */100 sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))101 bh.Data = sh.Data102 bh.Len = sh.Len103 bh.Cap = sh.Len104 return b105}106107func countParams(path string) uint16 {108 var n uint77 for i := range []byte(path) {78 switch path[i] {79 case ':', '*':80 n++81 }82 }109 s := strToBytes(path)110 n += uint(bytes.Count(s, strColon))111 n += uint(bytes.Count(s, strStar))112 return uint16(n)113}114115type nodeType uint8
75 unmodified lines
191 }192193 n.children = []*node{&child}194 // []byte for proper unicode char conversion, see #65166 n.indices = string([]byte{n.path[i]})195 n.indices = bytesToStr([]byte{n.path[i]})196 n.path = path[:i]197 n.handlers = nil198 n.wildChild = false199 n.fullPath = fullPath[:parentFullPathIndex+i]
51 unmodified lines
251252 // Otherwise insert it253 if c != ':' && c != '*' {254 // []byte for proper unicode char conversion, see #65226 n.indices += string([]byte{c})255 n.indices += bytesToStr([]byte{c})256 child := &node{257 fullPath: fullPath,258 }259 n.children = append(n.children, child)
540 unmodified lines