Skip to content
Myr

perf(recover): replace bytes with strings in function for better performance (#4252)

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

authored by Name · committed by GitHub · parent 61c2b1c · Browse files · 2 files+11 added−14 removed
This commit

State

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

Trailers

  • Co-authored-by: huangzw <huangzw@2345.com>

Diff stats

2 files+11 added−14 removed

  • other:+11 added−14 removed

2 files+11 added−14 removed

modified:recovery_test.go+2 added-2 removed
88 unmodified lines
89}9091func TestSource(t *testing.T) {92 bs := source(nil, 0)93 assert.Equal(t, dunno, bs)93 assert.Equal(t, dunnoBytes, bs)9495 in := [][]byte{96 []byte("Hello world."),97 []byte("Hi, gin.."),98 }99 bs = source(in, 10)100 assert.Equal(t, dunno, bs)100 assert.Equal(t, dunnoBytes, bs)101102 bs = source(in, 1)103 assert.Equal(t, []byte("Hello world."), bs)104}
143 unmodified lines
modified:recovery.go+9 added-12 removed
17 unmodified lines
18 "strings"19 "time"20)2122var (23 dunno = []byte("???")24 centerDot = []byte("·")25 dot = []byte(".")26 slash = []byte("/")27)22const dunno = "???"2324var dunnoBytes = []byte(dunno)2526// RecoveryFunc defines the function passable to CustomRecovery.27type RecoveryFunc func(c *Context, err any)2829// Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
104 unmodified lines
134// source returns a space-trimmed slice of the n'th line.135func source(lines [][]byte, n int) []byte {136 n-- // in stack trace, lines are 1-indexed but our array is 0-indexed137 if n < 0 || n >= len(lines) {141 return dunno138 return dunnoBytes139 }140 return bytes.TrimSpace(lines[n])141}142143// function returns, if possible, the name of the function containing the PC.147func function(pc uintptr) []byte {144func function(pc uintptr) string {145 fn := runtime.FuncForPC(pc)146 if fn == nil {147 return dunno148 }152 name := []byte(fn.Name())149 name := fn.Name()150 // The name includes the path name to the package, which is unnecessary151 // since the file name is already included. Plus, it has center dots.152 // That is, we see153 // runtime/debug.*T·ptrmethod154 // and want155 // *T.ptrmethod156 // Also the package path might contain dot (e.g. code.google.com/...),157 // so first eliminate the path prefix161 if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {158 if lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 {159 name = name[lastSlash+1:]160 }164 if period := bytes.Index(name, dot); period >= 0 {161 if period := strings.IndexByte(name, '.'); period >= 0 {162 name = name[period+1:]163 }167 name = bytes.ReplaceAll(name, centerDot, dot)164 name = strings.ReplaceAll(name, "·", ".")165 return name166}167168// timeFormat returns a customized time string for logger.
3 unmodified lines