From 59b4f47b225029068bf015117ada1a06d54fbd59 Mon Sep 17 00:00:00 2001 From: Clayton Coleman Date: Thu, 21 Mar 2019 20:57:36 -0400 Subject: [PATCH] Avoid 3 object creations when no dryRun parameter is provided These allocations should only occur rarely. ``` BenchmarkGet-12 100000 108013 ns/op 17732 B/op 149 allocs/op BenchmarkGet-12 100000 109045 ns/op 17608 B/op 146 allocs/op ``` --- .../apiserver/pkg/endpoints/metrics/metrics.go | 12 ++++++++++-- 1 file changed, 10 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 ecb5587c075..7c5154295ee 100644 --- a/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go +++ b/staging/src/k8s.io/apiserver/pkg/endpoints/metrics/metrics.go @@ -20,6 +20,7 @@ import ( "bufio" "net" "net/http" + "net/url" "regexp" "strconv" "strings" @@ -234,7 +235,7 @@ func RecordLongRunning(req *http.Request, requestInfo *request.RequestInfo, comp // a request. verb must be uppercase to be backwards compatible with existing monitoring tooling. func MonitorRequest(req *http.Request, verb, group, version, resource, subresource, scope, component, contentType string, httpCode, respSize int, elapsed time.Duration) { reportedVerb := cleanVerb(verb, req) - dryRun := cleanDryRun(req.URL.Query()["dryRun"]) + dryRun := cleanDryRun(req.URL) client := cleanUserAgent(utilnet.GetHTTPClient(req)) elapsedMicroseconds := float64(elapsed / time.Microsecond) elapsedSeconds := elapsed.Seconds() @@ -331,12 +332,19 @@ func cleanVerb(verb string, request *http.Request) string { return reportedVerb } -func cleanDryRun(dryRun []string) string { +func cleanDryRun(u *url.URL) string { + // avoid allocating when we don't see dryRun in the query + if !strings.Contains(u.RawQuery, "dryRun") { + return "" + } + dryRun := u.Query()["dryRun"] if errs := validation.ValidateDryRun(nil, dryRun); len(errs) > 0 { return "invalid" } // Since dryRun could be valid with any arbitrarily long length // we have to dedup and sort the elements before joining them together + // TODO: this is a fairly large allocation for what it does, consider + // a sort and dedup in a single pass return strings.Join(utilsets.NewString(dryRun...).List(), ",") }