Open gazerro opened 3 years ago
@gazerro if you would like to send a change I recommend working package by package to avoid review delays. Also please be aware that the code freeze is rapidly approaching at the end of the month. If you want to address this, please do not delay.
Actually the code freeze already happened. This would have to be for 1.18.
Welp, there you go.
@davecheney yes, I will send a CL for every single package.
Replacing occurrences in the
encoding/binary
package results in improvements in theWriteStruct
benchmark
That sounds to me like a missed optimization in the compiler — there doesn't seem to be any semantic reason why the two calls should differ, and even if we update all of the x.Type().Kind()
calls in the standard library there are likely plenty of similar calls in third-party packages.
The two calls differ if x
is the zero Value
, so the compiler may not always be able to do this optimization because it has to check the value of x
at runtime.
Seems like in most (all?) of these cases in the standard library, the compiler should already know that the value of x
is nonzero — either because the value passed to reflect.ValueOf
is invariantly non-nil,¹ or because the reflect.Value
is already known to be nonzero (due to a previous call or explicit check).
Yes, I think so. Optimization would be great. But in the standard library it would still be worth using one or the other consistently unless a specific behavior is desired.
For example the in the file src/internal/fmtsort/sort.go
, the code
func Sort(mapValue reflect.Value) *SortedMap {
if mapValue.Type().Kind() != reflect.Map {
return nil
}
...
}
for me it is not clear if the use of value.Type().Kind()
is intensional, to panic if value
is Invalid
, or not. If x.Kind()
were preferred to x.Type().Kind()
, I would interpret it as intentional.
In the file src/net/http/transport.go
, this code:
if rv := reflect.ValueOf(altProto["https"]); rv.IsValid() && rv.Type().Kind() == reflect.Struct && rv.Type().NumField() == 1 {
can be written as
if rv := reflect.ValueOf(altProto["https"]); rv.Kind() == reflect.Struct && rv.Type().NumField() == 1 {
even if the compiler can optimize it.
If you look at the code, all the cost is in computing the rv.Type() but both Kind()s are dirt cheap.
Moving this to the backlog, since it's already been pushed back once.
Change https://go.dev/cl/632635 mentions this issue: all: replace reflect.Value.Type.Kind with reflect.Value.Kind
If
x
is areflect.Value
value and it is not the zeroValue
,x.Kind()
can be used instead ofx.Type().Kind()
.There are many places in the standard library where this replacement can be done
Replacing occurrences in the
encoding/binary
package results in improvements in theWriteStruct
benchmark