From 33a266a2df76f0fdbbc03e912a763120a7f7c0ae Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 2 Oct 2026 15:56:19 +0200 Subject: [PATCH] fix(key): reduce String allocations --- lib/key/key.go | 5 ++++- lib/key/key_benchmark_test.go | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/key/key.go b/lib/key/key.go index 0514f350..0a5b2cac 100644 --- a/lib/key/key.go +++ b/lib/key/key.go @@ -19,7 +19,10 @@ type Key uint64 // String returns key in the text form used by JaWS. func (key Key) String() string { - return string(Append(nil, key)) + if key == 0 { + return "" + } + return strconv.FormatUint(uint64(key), 32) } // Parse parses a JaWS key prefix from its text form. diff --git a/lib/key/key_benchmark_test.go b/lib/key/key_benchmark_test.go index 8f836303..32c633bd 100644 --- a/lib/key/key_benchmark_test.go +++ b/lib/key/key_benchmark_test.go @@ -7,6 +7,7 @@ import ( ) var appendBenchSink []byte +var stringBenchSink string // BenchmarkAppend guards the base-32 encode hot path; it must stay // allocation-light when appending into an existing buffer. @@ -20,3 +21,12 @@ func BenchmarkAppend(b *testing.B) { appendBenchSink = key.Append(appendBenchSink[:0], benchmarkKey) } } + +// BenchmarkString guards the allocation cost of Key.String. +func BenchmarkString(b *testing.B) { + const benchmarkKey key.Key = 0x1234abcd + b.ReportAllocs() + for b.Loop() { + stringBenchSink = benchmarkKey.String() + } +}