perf(binding): use Go 1.25 reflect.TypeAssert API

This commit is contained in:
1911860538 2026-03-01 14:59:17 +08:00
parent cb2b764cc8
commit 13cd5f238d
2 changed files with 31 additions and 1 deletions

View File

@ -201,7 +201,7 @@ func trySetCustom(val string, value reflect.Value) (isSet bool, err error) {
func trySetUsingParser(val string, value reflect.Value, parser string) (isSet bool, err error) { func trySetUsingParser(val string, value reflect.Value, parser string) (isSet bool, err error) {
switch parser { switch parser {
case "encoding.TextUnmarshaler": case "encoding.TextUnmarshaler":
v, ok := value.Addr().Interface().(encoding.TextUnmarshaler) v, ok := reflect.TypeAssert[encoding.TextUnmarshaler](value)
if !ok { if !ok {
return false, nil return false, nil
} }

View File

@ -5,6 +5,7 @@
package binding package binding
import ( import (
"reflect"
"testing" "testing"
"time" "time"
@ -65,3 +66,32 @@ func BenchmarkMapFormName(b *testing.B) {
t := b t := b
assert.Equal(t, "mike", s.Name) assert.Equal(t, "mike", s.Name)
} }
// customUnmarshalTextString is a custom type that implements encoding.TextUnmarshaler.
// It stores the unmarshaled text in the Value field.
type customUnmarshalTextString struct {
Value string
}
func (t *customUnmarshalTextString) UnmarshalText(text []byte) error {
t.Value = string(text)
return nil
}
// BenchmarkTrySetUsingParserTextUnmarshaler benchmarks the performance of trySetUsingParser
// when using the "encoding.TextUnmarshaler" parser to unmarshal a string value.
func BenchmarkTrySetUsingParserTextUnmarshaler(b *testing.B) {
var target customUnmarshalTextString
value := reflect.ValueOf(&target).Elem()
testValue := "hello world"
parser := "encoding.TextUnmarshaler"
b.ResetTimer()
b.ReportAllocs()
for b.Loop() {
_, err := trySetUsingParser(testValue, value, parser)
if err != nil {
b.Fatal(err)
}
}
}