From 83c41eab1d6f55c9ccf61744bfc345c95d3a0664 Mon Sep 17 00:00:00 2001 From: Clayton Coleman Date: Thu, 21 Mar 2019 20:48:00 -0400 Subject: [PATCH] Avoid an allocation on all requests when checking for an old user agent ReplaceAllStrings always allocates, while scanning a relatively short regex twice is slightly more CPU immediately but less later. ``` BenchmarkGet-12 100000 108824 ns/op 17818 B/op 152 allocs/op BenchmarkGet-12 100000 108013 ns/op 17732 B/op 149 allocs/op ``` --- .../src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go b/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go index cbe632d14ec..ecb5587c075 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go @@ -34,7 +34,7 @@ import ( "k8s.io/apiserver/pkg/features" utilfeature "k8s.io/apiserver/pkg/util/feature" - "github.com/emicklei/go-restful" + restful "github.com/emicklei/go-restful" "github.com/prometheus/client_golang/prometheus" ) @@ -346,7 +346,10 @@ func cleanUserAgent(ua string) string { return "Browser" } // If an old "kubectl.exe" has passed us its full path, we discard the path portion. - ua = kubectlExeRegexp.ReplaceAllString(ua, "$1") + if kubectlExeRegexp.MatchString(ua) { + // avoid an allocation + ua = kubectlExeRegexp.ReplaceAllString(ua, "$1") + } return ua }