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.
This commit is contained in:
Clayton Coleman 2019-03-25 17:09:49 -04:00
parent 0603331ea8
commit b405cdf85b
No known key found for this signature in database
GPG Key ID: 3D16906B4F1C5CB3

View File

@ -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