Skip to content

Commit

Permalink
encoding/json: rely on reflect.Value.SetZero
Browse files Browse the repository at this point in the history
v.SetZero() is faster than v.Set(reflect.Zero(v.Type()))
and was recently added in Go 1.20.

Benchmark numbers are largely unchanged since this mainly
affects the unmarshaling of large numbers of JSON nulls,
which our benchmarks do not heavily exercise.

Change-Id: I464f60f63c9027e63a99fd5da92e7ab782018329
Reviewed-on: https://go-review.googlesource.com/c/go/+/471195
Reviewed-by: Johan Brandhorst-Satzkorn <[email protected]>
TryBot-Result: Gopher Robot <[email protected]>
Reviewed-by: Than McIntosh <[email protected]>
Run-TryBot: Joseph Tsai <[email protected]>
Reviewed-by: Dmitri Shuralyov <[email protected]>
Auto-Submit: Joseph Tsai <[email protected]>
Reviewed-by: Daniel Martí <[email protected]>
  • Loading branch information
dsnet authored and gopherbot committed Feb 27, 2023
1 parent 8367e2d commit cb3e170
Showing 1 changed file with 4 additions and 6 deletions.
10 changes: 4 additions & 6 deletions src/encoding/json/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -577,13 +577,11 @@ func (d *decodeState) array(v reflect.Value) error {

if i < v.Len() {
if v.Kind() == reflect.Array {
// Array. Zero the rest.
z := reflect.Zero(v.Type().Elem())
for ; i < v.Len(); i++ {
v.Index(i).Set(z)
v.Index(i).SetZero() // zero remainder of array
}
} else {
v.SetLen(i)
v.SetLen(i) // truncate the slice
}
}
if i == 0 && v.Kind() == reflect.Slice {
Expand Down Expand Up @@ -688,7 +686,7 @@ func (d *decodeState) object(v reflect.Value) error {
if !mapElem.IsValid() {
mapElem = reflect.New(elemType).Elem()
} else {
mapElem.Set(reflect.Zero(elemType))
mapElem.SetZero()
}
subv = mapElem
} else {
Expand Down Expand Up @@ -902,7 +900,7 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool
}
switch v.Kind() {
case reflect.Interface, reflect.Pointer, reflect.Map, reflect.Slice:
v.Set(reflect.Zero(v.Type()))
v.SetZero()
// otherwise, ignore null for primitives/string
}
case 't', 'f': // true, false
Expand Down

0 comments on commit cb3e170

Please sign in to comment.