From b3561401fd1ad7ba849de85746dca7c34c4509f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Martins?= Date: Mon, 28 Dec 2020 14:54:40 +0100 Subject: [PATCH] pkg/util/net: replace bytes.Buffer with strings.Builder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit strings.Builder has better performance over bytes.Buffer for building strings: Benchmark results: ``` name old time/op new time/op delta _ParseQuotedString-8 146ns ±20% 105ns ± 2% -28.14% (p=0.008 n=5+5) name old alloc/op new alloc/op delta _ParseQuotedString-8 80.0B ± 0% 24.0B ± 0% -70.00% (p=0.008 n=5+5) name old allocs/op new allocs/op delta _ParseQuotedString-8 2.00 ± 0% 2.00 ± 0% ~ (all equal) ``` Signed-off-by: André Martins --- .../k8s.io/apimachinery/pkg/util/net/http.go | 2 +- .../apimachinery/pkg/util/net/http_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/http.go b/staging/src/k8s.io/apimachinery/pkg/util/net/http.go index ba63d02df69..567a294e26c 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/http.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/http.go @@ -693,7 +693,7 @@ func parseQuotedString(quotedString string) (string, string, error) { var remainder string escaping := false closedQuote := false - result := &bytes.Buffer{} + result := &strings.Builder{} loop: for i := 0; i < len(quotedString); i++ { b := quotedString[i] diff --git a/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go b/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go index a43161b88b7..9411bfa7ddf 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/net/http_test.go @@ -1107,3 +1107,21 @@ func TestPingTimeoutSeconds(t *testing.T) { } reset() } + +func Benchmark_ParseQuotedString(b *testing.B) { + str := `"The quick brown" fox jumps over the lazy dog` + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + quoted, remainder, err := parseQuotedString(str) + if err != nil { + b.Errorf("Unexpected error %s", err) + } + if quoted != "The quick brown" { + b.Errorf("Unexpected quoted string %s", quoted) + } + if remainder != "fox jumps over the lazy dog" { + b.Errorf("Unexpected remainder string %s", quoted) + } + } +}