From a1638bf6333adeb9e466a8af27ac3e926c31d2e1 Mon Sep 17 00:00:00 2001 From: Patrick Ohly Date: Thu, 22 Dec 2022 17:09:45 +0100 Subject: [PATCH] KObj: optimize string concatenation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Using a strings.Builder reduces the number of allocations: name old time/op new time/op delta KlogOutput/KObjSlice_okay-36 15.2µs ± 5% 14.8µs ± 4% ~ (p=0.151 n=5+5) KlogOutput/KObjSlice_nil_entry-36 14.4µs ± 5% 13.6µs ± 3% -5.25% (p=0.032 n=5+5) KlogOutput/KObj-36 13.5µs ± 8% 13.5µs ± 6% ~ (p=0.841 n=5+5) KlogOutput/KObjSlice_ints-36 15.3µs ± 5% 15.2µs ± 4% ~ (p=0.841 n=5+5) KlogOutput/KObjSlice_nil_arg-36 12.8µs ± 2% 12.8µs ± 6% ~ (p=0.841 n=5+5) KlogOutput/KObjSlice_int_arg-36 14.1µs ± 4% 13.8µs ± 3% ~ (p=0.310 n=5+5) KlogOutput/KObjs-36 14.1µs ± 8% 13.6µs ± 8% ~ (p=0.690 n=5+5) name old alloc/op new alloc/op delta KlogOutput/KObjSlice_okay-36 2.89kB ± 0% 2.82kB ± 0% -2.23% (p=0.008 n=5+5) KlogOutput/KObjSlice_nil_entry-36 2.65kB ± 0% 2.62kB ± 0% ~ (p=0.079 n=4+5) KlogOutput/KObj-36 2.50kB ± 0% 2.47kB ± 0% -1.30% (p=0.000 n=4+5) KlogOutput/KObjSlice_ints-36 2.90kB ± 0% 2.90kB ± 0% ~ (p=1.000 n=5+5) KlogOutput/KObjSlice_nil_arg-36 2.41kB ± 0% 2.41kB ± 0% ~ (all equal) KlogOutput/KObjSlice_int_arg-36 2.67kB ± 0% 2.67kB ± 0% ~ (all equal) KlogOutput/KObjs-36 2.72kB ± 0% 2.65kB ± 0% -2.38% (p=0.008 n=5+5) name old allocs/op new allocs/op delta KlogOutput/KObjSlice_okay-36 46.0 ± 0% 42.0 ± 0% -8.70% (p=0.008 n=5+5) KlogOutput/KObjSlice_nil_entry-36 40.0 ± 0% 38.0 ± 0% -5.00% (p=0.008 n=5+5) KlogOutput/KObj-36 36.0 ± 0% 34.0 ± 0% -5.56% (p=0.008 n=5+5) KlogOutput/KObjSlice_ints-36 39.0 ± 0% 39.0 ± 0% ~ (all equal) KlogOutput/KObjSlice_nil_arg-36 35.0 ± 0% 35.0 ± 0% ~ (all equal) KlogOutput/KObjSlice_int_arg-36 37.0 ± 0% 37.0 ± 0% ~ (all equal) KlogOutput/KObjs-36 42.0 ± 0% 38.0 ± 0% -9.52% (p=0.008 n=5+5) --- k8s_references.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/k8s_references.go b/k8s_references.go index 2c218f698..a6436b5d1 100644 --- a/k8s_references.go +++ b/k8s_references.go @@ -19,6 +19,7 @@ package klog import ( "fmt" "reflect" + "strings" "github.com/go-logr/logr" ) @@ -31,7 +32,12 @@ type ObjectRef struct { func (ref ObjectRef) String() string { if ref.Namespace != "" { - return fmt.Sprintf("%s/%s", ref.Namespace, ref.Name) + var builder strings.Builder + builder.Grow(len(ref.Namespace) + len(ref.Name) + 1) + builder.WriteString(ref.Namespace) + builder.WriteRune('/') + builder.WriteString(ref.Name) + return builder.String() } return ref.Name }