From b405cdf85b9e0d3a6f3d498e1ee32b2a582882f6 Mon Sep 17 00:00:00 2001 From: Clayton Coleman Date: Mon, 25 Mar 2019 17:09:49 -0400 Subject: [PATCH] Reduce allocations in metav1.Time JSON serialization Time has a limited set of allowed characters and so can bypass part of the expensive checking done for valid JSON characters. ``` BenchmarkGet-12 10000 111846 ns/op 17273 B/op 130 allocs/op BenchmarkWatchHTTP-12 50000 37830 ns/op 1886 B/op 29 allocs/op BenchmarkGet-12 20000 115917 ns/op 17344 B/op 130 allocs/op BenchmarkWatchHTTP-12 50000 36741 ns/op 1775 B/op 24 allocs/op ``` Can improve CRD watch performance by 5-10% for small objects. --- .../src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go index efff656e109..79904fd7943 100644 --- a/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go +++ b/staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/time.go @@ -20,7 +20,7 @@ import ( "encoding/json" "time" - "github.com/google/gofuzz" + fuzz "github.com/google/gofuzz" ) // Time is a wrapper around time.Time which supports correct @@ -147,8 +147,12 @@ func (t Time) MarshalJSON() ([]byte, error) { // Encode unset/nil objects as JSON's "null". return []byte("null"), nil } - - return json.Marshal(t.UTC().Format(time.RFC3339)) + buf := make([]byte, 0, len(time.RFC3339)+2) + buf = append(buf, '"') + // time cannot contain non escapable JSON characters + buf = t.UTC().AppendFormat(buf, time.RFC3339) + buf = append(buf, '"') + return buf, nil } // OpenAPISchemaType is used by the kube-openapi generator when constructing