]> Cypherpunks repositories - gostls13.git/commitdiff
reflect, internal/abi: speed up TypeFor[T]
authorMateusz Poliwczak <mpoliwczak34@gmail.com>
Wed, 12 Feb 2025 07:16:32 +0000 (07:16 +0000)
committerGopher Robot <gobot@golang.org>
Thu, 13 Feb 2025 02:31:00 +0000 (18:31 -0800)
goos: linux
goarch: amd64
pkg: reflect
cpu: AMD Ryzen 5 4600G with Radeon Graphics
                 │ /tmp/before  │              /tmp/after              │
                 │    sec/op    │    sec/op     vs base                │
TypeForString-12    2.091n ± 1%    1.174n ± 1%  -43.84% (p=0.000 n=20)
TypeForError-12    7.5810n ± 3%   0.9372n ± 1%  -87.64% (p=0.000 n=20)

Change-Id: I22022f99b2dd2029f02d9ed8477b209adf7e9496
GitHub-Last-Rev: 64d2ac5bb2f3b2a659663832a4641ff4fc83bddd
GitHub-Pull-Request: golang/go#71654
Reviewed-on: https://go-review.googlesource.com/c/go/+/648395
LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: Cherry Mui <cherryyz@google.com>
Auto-Submit: Ian Lance Taylor <iant@google.com>

src/internal/abi/type.go
src/reflect/type.go

index 1c1793fcf5ba3751d6314f93662174fd47242f38..4671b0da2848f32f4f3b9d79a28de8ebee30a13c 100644 (file)
@@ -187,11 +187,7 @@ func TypeOf(a any) *Type {
 
 // TypeFor returns the abi.Type for a type parameter.
 func TypeFor[T any]() *Type {
-       var v T
-       if t := TypeOf(v); t != nil {
-               return t // optimize for T being a non-interface kind
-       }
-       return TypeOf((*T)(nil)).Elem() // only for an interface kind
+       return (*PtrType)(unsafe.Pointer(TypeOf((*T)(nil)))).Elem
 }
 
 func (t *Type) Kind() Kind { return t.Kind_ & KindMask }
index 0e41a6db992e1cd202dcb484ac0eb2cd56bbee2e..e5ee7f90d0202c11ab14de1d90dea72ffd83e1cc 100644 (file)
@@ -1303,6 +1303,11 @@ func TypeOf(i any) Type {
        return toType(abi.TypeOf(i))
 }
 
+// TypeFor returns the [Type] that represents the type argument T.
+func TypeFor[T any]() Type {
+       return toType(abi.TypeFor[T]())
+}
+
 // rtypeOf directly extracts the *rtype of the provided value.
 func rtypeOf(i any) *abi.Type {
        return abi.TypeOf(i)
@@ -2850,12 +2855,3 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
                }
        }
 }
-
-// TypeFor returns the [Type] that represents the type argument T.
-func TypeFor[T any]() Type {
-       var v T
-       if t := TypeOf(v); t != nil {
-               return t // optimize for T being a non-interface kind
-       }
-       return TypeOf((*T)(nil)).Elem() // only for an interface kind
-}