The type assertion would involve call to runtime.assertE2T or runtime.assertE2I (you could see the assembly codes).
package main
import (
"fmt"
"time"
)
type I interface {
echo()
}
type A struct{}
func (a *A) echo() {}
type testfn func()
func run(f testfn) {
ts := time.Now()
f()
te := time.Now()
fmt.Println(te.Sub(ts))
}
func testE2T() {
var i interface{} = new(A)
for a := 0; a < 500000000; a++ {
_ = i.(*A)
}
}
func testE2I() {
var i interface{} = new(A)
for a := 0; a < 500000000; a++ {
_ = i.(I)
}
}
func main() {
fmt.Println("testE2I:")
run(testE2I)
fmt.Println("testE2T:")
run(testE2T)
}
result:
testE2I:
11.065225934s
testE2T:
5.720773381s
It seems that the type assertion is slower than the pointer cast in C? How to explain it?
And it's strange that when I use gccgo to run the same program, it would cause out-of-memory error. Does the gccgo has some limitation in gc?