♻️ 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
}
var (
index int
character rune
lastElementEndsAt int
insertIndex int
)
for index, character = range headerValue + "$" {
if character == ',' || index == len(headerValue) {
if insertIndex >= len(dst) {
oldSlice := dst
dst = make([]string, len(dst)+(len(dst)>>1)+2)
copy(dst, oldSlice)
}
dst[insertIndex] = utils.TrimLeft(headerValue[lastElementEndsAt:index], ' ')
lastElementEndsAt = index + 1
insertIndex++
dst = dst[:0]
segmentStart := 0
isLeadingSpace := true
for i, c := range headerValue {
switch {
case c == ',':
dst = append(dst, headerValue[segmentStart:i])
segmentStart = i + 1
isLeadingSpace = true
case c == ' ' && isLeadingSpace:
segmentStart = i + 1
default:
isLeadingSpace = false
}
}
dst = append(dst, headerValue[segmentStart:])
if len(dst) > insertIndex {
dst = dst[:insertIndex]
}
return dst
}

View File

@ -303,6 +303,26 @@ func Test_Utils_GetSplicedStrList(t *testing.T) {
headerValue: "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 {