This is a follow-up for #17118 .
Currently in go tip single return value type assertion is much slower comparing to type assertion returning two values:
func BenchmarkTypeAssertSingleReturnValue(b *testing.B) {
n := 42
v := interface{}(n)
for i := 0; i < b.N; i++ {
a := v.(int)
if a != n {
b.Fatalf("unexpected a: %d. Expecting %d", a, n)
}
}
}
func BenchmarkTypeAssertTwoReturnValues(b *testing.B) {
n := 42
v := interface{}(n)
for i := 0; i < b.N; i++ {
a, ok := v.(int)
if !ok {
b.Fatalf("type assertion failed for v=%v", v)
}
if a != n {
b.Fatalf("unexpected a: %d. Expecting %d", a, n)
}
}
}
Results:
BenchmarkTypeAssertSingleReturnValue-4 200000000 7.97 ns/op 0 B/op 0 allocs/op
BenchmarkTypeAssertTwoReturnValues-4 2000000000 1.09 ns/op 0 B/op 0 allocs/op
The compiler may optimize single return value type assertion (x := v.(T)) by rewriting it into the following code:
x, ok := v.(T)
if !ok {
panic(...)
}
This is a follow-up for #17118 .
Currently in go tip single return value type assertion is much slower comparing to type assertion returning two values:
Results:
The compiler may optimize single return value type assertion (
x := v.(T)) by rewriting it into the following code: