perf(spec): using string.Builder instead of concatenation

This commit is contained in:
verse91
2026-04-11 20:56:16 +07:00
parent 1f483c5ab2
commit 81b80d079c
+11 -12
View File
@@ -161,13 +161,14 @@ func Lookup(input string) []Suggestion {
} }
// build prefix from tokens consumed so far // build prefix from tokens consumed so far
prefix := "" var prefixBuilder strings.Builder
for i := 0; i < depth; i++ { for i := 0; i < depth; i++ {
if i > 0 { if i > 0 {
prefix += " " prefixBuilder.WriteByte(' ')
} }
prefix += tokens[i] prefixBuilder.WriteString(tokens[i])
} }
prefix := prefixBuilder.String()
// partial is what user is currently typing (might be incomplete) // partial is what user is currently typing (might be incomplete)
partial := "" partial := ""
@@ -281,7 +282,7 @@ func topLevelSuggestions(query string) []Suggestion {
func tokenize(s string) []string { func tokenize(s string) []string {
tokens := []string{} tokens := []string{}
current := "" var current strings.Builder
inQuote := false inQuote := false
var quoteChar rune var quoteChar rune
@@ -293,20 +294,18 @@ func tokenize(s string) []string {
case inQuote && c == quoteChar: case inQuote && c == quoteChar:
inQuote = false inQuote = false
case c == ' ' && !inQuote: case c == ' ' && !inQuote:
if current != "" { if current.Len() > 0 {
tokens = append(tokens, current) tokens = append(tokens, current.String())
current = "" current.Reset()
} else if len(tokens) > 0 && tokens[len(tokens)-1] != "" { } else if len(tokens) > 0 && tokens[len(tokens)-1] != "" {
// preserve trailing space as an empty token for suggestions // preserve trailing space
// but only if it's the very last thing and not multiple spaces
} }
default: default:
current += string(c) current.WriteRune(c)
} }
} }
// always append the last token (even if empty, representing the cursor position) tokens = append(tokens, current.String())
tokens = append(tokens, current)
return tokens return tokens
} }