refactor: use strings.Builder to improve performance (#7364)

* refactor: use strings.Builder to improve performance

Signed-off-by: zjumathcode <pai314159@2980.com>

* refactor: small builder improvements per review (WriteByte / split writes)

also revert builder change in client_test.go

refactor(logging): build IP mask output via join of parts (more efficient)

---------

Signed-off-by: zjumathcode <pai314159@2980.com>
Co-authored-by: Francis Lavoie <lavofr@gmail.com>
This commit is contained in:
zjumathcode 2026-02-17 03:30:44 +08:00 committed by GitHub
parent 8a18acc025
commit 68d50020ee
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 12 deletions

View File

@ -18,6 +18,7 @@ import (
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/caddyserver/caddy/v2"
)
@ -110,14 +111,16 @@ func (r Route) Empty() bool {
}
func (r Route) String() string {
handlersRaw := "["
var handlersRaw strings.Builder
handlersRaw.WriteByte('[')
for _, hr := range r.HandlersRaw {
handlersRaw += " " + string(hr)
handlersRaw.WriteByte(' ')
handlersRaw.WriteString(string(hr))
}
handlersRaw += "]"
handlersRaw.WriteByte(']')
return fmt.Sprintf(`{Group:"%s" MatcherSetsRaw:%s HandlersRaw:%s Terminal:%t}`,
r.Group, r.MatcherSetsRaw, handlersRaw, r.Terminal)
r.Group, r.MatcherSetsRaw, handlersRaw.String(), r.Terminal)
}
// Provision sets up both the matchers and handlers in the route.
@ -440,13 +443,15 @@ func (ms *MatcherSets) FromInterface(matcherSets any) error {
// TODO: Is this used?
func (ms MatcherSets) String() string {
result := "["
var result strings.Builder
result.WriteByte('[')
for _, matcherSet := range ms {
for _, matcher := range matcherSet {
result += fmt.Sprintf(" %#v", matcher)
result.WriteString(fmt.Sprintf(" %#v", matcher))
}
}
return result + " ]"
result.WriteByte(']')
return result.String()
}
var routeGroupCtxKey = caddy.CtxKey("route_group")

View File

@ -255,7 +255,7 @@ func (m IPMaskFilter) Filter(in zapcore.Field) zapcore.Field {
}
func (m IPMaskFilter) mask(s string) string {
output := ""
parts := make([]string, 0)
for value := range strings.SplitSeq(s, ",") {
value = strings.TrimSpace(value)
host, port, err := net.SplitHostPort(value)
@ -264,7 +264,7 @@ func (m IPMaskFilter) mask(s string) string {
}
ipAddr := net.ParseIP(host)
if ipAddr == nil {
output += value + ", "
parts = append(parts, value)
continue
}
mask := m.v4Mask
@ -273,13 +273,13 @@ func (m IPMaskFilter) mask(s string) string {
}
masked := ipAddr.Mask(mask)
if port == "" {
output += masked.String() + ", "
parts = append(parts, masked.String())
continue
}
output += net.JoinHostPort(masked.String(), port) + ", "
parts = append(parts, net.JoinHostPort(masked.String(), port))
}
return strings.TrimSuffix(output, ", ")
return strings.Join(parts, ", ")
}
type filterAction string