From f018db89101d555a220d643a6be7a712c0e320eb Mon Sep 17 00:00:00 2001 From: Mathias Bogaert Date: Sat, 3 Jan 2026 13:44:26 +0000 Subject: [PATCH] perf(trace): optimize traceSingleQuotedString Replace fmt.Fprintf with direct hex encoding using lookup table. Add Grow() pre-allocation to eliminate builder reallocations. Benchmarks show 1.7-8x speedup depending on input: - all non-printable: 743ns -> 92ns (8x) - mixed content: 422ns -> 108ns (4x) - printable only: 242ns -> 144ns (1.7x) Allocations reduced from 2-6 to 1 in all cases. Signed-off-by: Mathias Bogaert --- pgproto3/trace.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pgproto3/trace.go b/pgproto3/trace.go index 6cc7d3e36..cc506beb1 100644 --- a/pgproto3/trace.go +++ b/pgproto3/trace.go @@ -397,15 +397,20 @@ func traceDoubleQuotedString(buf []byte) string { return `"` + string(buf) + `"` } +const hexChars = "0123456789abcdef" + // traceSingleQuotedString returns buf as a single-quoted string with non-printable characters hex-escaped. It is // roughly equivalent to pqTraceOutputNchar in libpq. func traceSingleQuotedString(buf []byte) string { sb := &strings.Builder{} + sb.Grow(len(buf)*4 + 2) // worst case: every byte escaped (\xNN) + quotes sb.WriteByte('\'') for _, b := range buf { if b < 32 || b > 126 { - fmt.Fprintf(sb, `\x%x`, b) + sb.WriteString(`\x`) + sb.WriteByte(hexChars[b>>4]) + sb.WriteByte(hexChars[b&0x0f]) } else { sb.WriteByte(b) }