Skip to content

perf(stringutil): optimize Format #1583

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
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
60 changes: 52 additions & 8 deletions internal/stringutil/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,62 @@ package stringutil

import (
"fmt"
"regexp"
"strconv"
"strings"
)

var placeholderRegexp = regexp.MustCompile(`{(\d+)}`)
const maxInt = int(^uint(0) >> 1)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd eliminate this and just use math.MaxInt.


func Format(text string, args []any) string {
return placeholderRegexp.ReplaceAllStringFunc(text, func(match string) string {
index, err := strconv.ParseInt(match[1:len(match)-1], 10, 0)
if err != nil || int(index) >= len(args) {
if !strings.Contains(text, "{") {
return text
}

var b strings.Builder
b.Grow(len(text) + len(text)/4)

for i := 0; i < len(text); {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel wary about the amount of code used here; it's a lot of string/index finagling.

Can this instead be replaced by a loop where we use strings.IndexByte or strings.Cut to find the next { or }, along with slicing text as we go along?

if text[i] != '{' {
j := i + 1
for j < len(text) && text[j] != '{' {
j++
}
b.WriteString(text[i:j])
i = j
continue
}

j := i + 1
if j >= len(text) || text[j] < '0' || text[j] > '9' {
b.WriteByte('{')
i++
continue
}

k := j
for k < len(text) && text[k] >= '0' && text[k] <= '9' {
k++
}
if k >= len(text) || text[k] != '}' {
b.WriteByte('{')
i++
continue
}

n := 0
for p := j; p < k; p++ {
d := int(text[p] - '0')
if n > (maxInt-d)/10 {
panic("Invalid formatting placeholder")
}
n = n*10 + d
}
if n >= len(args) {
panic("Invalid formatting placeholder")
}
return fmt.Sprintf("%v", args[int(index)])
})

b.WriteString(fmt.Sprint(args[n]))
i = k + 1
}

return b.String()
}
Loading