From 3c12d2a80e40930632fc4a4a4e1a45140f33fb12 Mon Sep 17 00:00:00 2001 From: Name <1911860538@qq.com> Date: Sat, 31 May 2025 08:41:13 +0800 Subject: [PATCH] perf(recover): replace bytes with strings in function for better performance (#4252) Co-authored-by: huangzw --- recovery.go | 21 +++++++++------------ recovery_test.go | 4 ++-- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/recovery.go b/recovery.go index 8e4633b4..b3543e42 100644 --- a/recovery.go +++ b/recovery.go @@ -19,12 +19,9 @@ import ( "time" ) -var ( - dunno = []byte("???") - centerDot = []byte("·") - dot = []byte(".") - slash = []byte("/") -) +const dunno = "???" + +var dunnoBytes = []byte(dunno) // RecoveryFunc defines the function passable to CustomRecovery. type RecoveryFunc func(c *Context, err any) @@ -138,18 +135,18 @@ func stack(skip int) []byte { func source(lines [][]byte, n int) []byte { n-- // in stack trace, lines are 1-indexed but our array is 0-indexed if n < 0 || n >= len(lines) { - return dunno + return dunnoBytes } return bytes.TrimSpace(lines[n]) } // function returns, if possible, the name of the function containing the PC. -func function(pc uintptr) []byte { +func function(pc uintptr) string { fn := runtime.FuncForPC(pc) if fn == nil { return dunno } - name := []byte(fn.Name()) + name := fn.Name() // The name includes the path name to the package, which is unnecessary // since the file name is already included. Plus, it has center dots. // That is, we see @@ -158,13 +155,13 @@ func function(pc uintptr) []byte { // *T.ptrmethod // Also the package path might contain dot (e.g. code.google.com/...), // so first eliminate the path prefix - if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 { + if lastSlash := strings.LastIndexByte(name, '/'); lastSlash >= 0 { name = name[lastSlash+1:] } - if period := bytes.Index(name, dot); period >= 0 { + if period := strings.IndexByte(name, '.'); period >= 0 { name = name[period+1:] } - name = bytes.ReplaceAll(name, centerDot, dot) + name = strings.ReplaceAll(name, "·", ".") return name } diff --git a/recovery_test.go b/recovery_test.go index 08eec1e4..a6e61a97 100644 --- a/recovery_test.go +++ b/recovery_test.go @@ -90,14 +90,14 @@ func TestPanicWithAbort(t *testing.T) { func TestSource(t *testing.T) { bs := source(nil, 0) - assert.Equal(t, dunno, bs) + assert.Equal(t, dunnoBytes, bs) in := [][]byte{ []byte("Hello world."), []byte("Hi, gin.."), } bs = source(in, 10) - assert.Equal(t, dunno, bs) + assert.Equal(t, dunnoBytes, bs) bs = source(in, 1) assert.Equal(t, []byte("Hello world."), bs)