Skip to content
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

chore(performance): improve countParams #2378

Merged
merged 5 commits into from
May 17, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
chore: improve countParams performance
  • Loading branch information
appleboy committed May 17, 2020
commit 8467ce7abc9c39dcb05f260a1934cbe184e05f4c
35 changes: 25 additions & 10 deletions tree.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,20 @@
package gin

import (
"bytes"
"net/url"
"reflect"
"strings"
"unicode"
"unicode/utf8"
"unsafe"
)

var (
strColon = []byte(":")
strStar = []byte("*")
)

// Param is a single URL parameter, consisting of a key and a value.
type Param struct {
Key string
Expand Down Expand Up @@ -41,10 +48,6 @@ func (ps Params) ByName(name string) (va string) {
return
}

func bytesToStr(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

type methodTree struct {
method string
root *node
Expand Down Expand Up @@ -77,14 +80,26 @@ func longestCommonPrefix(a, b string) int {
return i
}

func bytesToStr(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}

func strToBytes(s string) (b []byte) {
/* #nosec G103 */
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
/* #nosec G103 */
sh := *(*reflect.StringHeader)(unsafe.Pointer(&s))
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return b
}

func countParams(path string) uint16 {
var n uint
for i := range []byte(path) {
switch path[i] {
case ':', '*':
n++
}
}
s := strToBytes(path)
n += uint(bytes.Count(s, strColon))
n += uint(bytes.Count(s, strStar))
return uint16(n)
}

Expand Down
14 changes: 14 additions & 0 deletions tree_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,20 @@ func TestCountParams(t *testing.T) {
}
}

var s = strings.Repeat("/:param", 5)

func BenchmarkCountParamsOld(b *testing.B) {
for i := 0; i < b.N; i++ {
countParamsOld(s)
}
}

func BenchmarkCountParams(b *testing.B) {
for i := 0; i < b.N; i++ {
countParamsNew(s)
}
}

func TestTreeAddAndGet(t *testing.T) {
tree := &node{}

Expand Down