Skip to content

Commit 679cd8e

Browse files
mateusz834gopherbot
authored andcommitted
reflect, internal/abi: speed up TypeFor[T]
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: 64d2ac5 GitHub-Pull-Request: #71654 Reviewed-on: https://go-review.googlesource.com/c/go/+/648395 LUCI-TryBot-Result: Go LUCI <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: Cherry Mui <[email protected]> Auto-Submit: Ian Lance Taylor <[email protected]>
1 parent fb5f78a commit 679cd8e

File tree

2 files changed

+6
-14
lines changed

2 files changed

+6
-14
lines changed

src/internal/abi/type.go

+1-5
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,7 @@ func TypeOf(a any) *Type {
187187

188188
// TypeFor returns the abi.Type for a type parameter.
189189
func TypeFor[T any]() *Type {
190-
var v T
191-
if t := TypeOf(v); t != nil {
192-
return t // optimize for T being a non-interface kind
193-
}
194-
return TypeOf((*T)(nil)).Elem() // only for an interface kind
190+
return (*PtrType)(unsafe.Pointer(TypeOf((*T)(nil)))).Elem
195191
}
196192

197193
func (t *Type) Kind() Kind { return t.Kind_ & KindMask }

src/reflect/type.go

+5-9
Original file line numberDiff line numberDiff line change
@@ -1303,6 +1303,11 @@ func TypeOf(i any) Type {
13031303
return toType(abi.TypeOf(i))
13041304
}
13051305

1306+
// TypeFor returns the [Type] that represents the type argument T.
1307+
func TypeFor[T any]() Type {
1308+
return toType(abi.TypeFor[T]())
1309+
}
1310+
13061311
// rtypeOf directly extracts the *rtype of the provided value.
13071312
func rtypeOf(i any) *abi.Type {
13081313
return abi.TypeOf(i)
@@ -2850,12 +2855,3 @@ func addTypeBits(bv *bitVector, offset uintptr, t *abi.Type) {
28502855
}
28512856
}
28522857
}
2853-
2854-
// TypeFor returns the [Type] that represents the type argument T.
2855-
func TypeFor[T any]() Type {
2856-
var v T
2857-
if t := TypeOf(v); t != nil {
2858-
return t // optimize for T being a non-interface kind
2859-
}
2860-
return TypeOf((*T)(nil)).Elem() // only for an interface kind
2861-
}

0 commit comments

Comments
 (0)