♻️ Refactor: Improve Performance of getSplicedStrList (#3318)

* ♻️ Refactor: improve performance of getSplicedStrList

goos: linux
goarch: amd64
pkg: github.com/gofiber/fiber/v3
cpu: AMD EPYC 7763 64-Core Processor
                           │   old.txt   │               new.txt               │
                           │   sec/op    │   sec/op     vs base                │
_Utils_GetSplicedStrList-4   66.12n ± 1%   51.05n ± 1%  -22.79% (p=0.000 n=50)

                           │  old.txt   │            new.txt             │
                           │    B/op    │    B/op     vs base            │
_Utils_GetSplicedStrList-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=50) ¹
¹ all samples are equal

                           │  old.txt   │            new.txt             │
                           │ allocs/op  │ allocs/op   vs base            │
_Utils_GetSplicedStrList-4   0.000 ± 0%   0.000 ± 0%  ~ (p=1.000 n=50) ¹
¹ all samples are equal

* 🚨 Test: add more test for getSplicedStrList

* 🩹 Fix: golangci-lint ifElseChain

* ♻️ Refactor: use more descriptive variable names
pull/3324/head
Kashiwa 2025-02-24 15:13:47 +08:00 committed by GitHub
parent ef4effc8a0
commit 0d1ade4626
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 34 additions and 19 deletions

View File

@ -321,28 +321,23 @@ func getSplicedStrList(headerValue string, dst []string) []string {
return nil return nil
} }
var ( dst = dst[:0]
index int segmentStart := 0
character rune isLeadingSpace := true
lastElementEndsAt int for i, c := range headerValue {
insertIndex int switch {
) case c == ',':
for index, character = range headerValue + "$" { dst = append(dst, headerValue[segmentStart:i])
if character == ',' || index == len(headerValue) { segmentStart = i + 1
if insertIndex >= len(dst) { isLeadingSpace = true
oldSlice := dst case c == ' ' && isLeadingSpace:
dst = make([]string, len(dst)+(len(dst)>>1)+2) segmentStart = i + 1
copy(dst, oldSlice) default:
} isLeadingSpace = false
dst[insertIndex] = utils.TrimLeft(headerValue[lastElementEndsAt:index], ' ')
lastElementEndsAt = index + 1
insertIndex++
} }
} }
dst = append(dst, headerValue[segmentStart:])
if len(dst) > insertIndex {
dst = dst[:insertIndex]
}
return dst return dst
} }

View File

@ -303,6 +303,26 @@ func Test_Utils_GetSplicedStrList(t *testing.T) {
headerValue: "gzip,", headerValue: "gzip,",
expectedList: []string{"gzip", ""}, expectedList: []string{"gzip", ""},
}, },
{
description: "has a space between words",
headerValue: " foo bar, hello world",
expectedList: []string{"foo bar", "hello world"},
},
{
description: "single comma",
headerValue: ",",
expectedList: []string{"", ""},
},
{
description: "multiple comma",
headerValue: ",,",
expectedList: []string{"", "", ""},
},
{
description: "comma with space",
headerValue: ", ,",
expectedList: []string{"", "", ""},
},
} }
for _, tc := range testCases { for _, tc := range testCases {