golang:如何解释类​​型声明效率? [关闭]

golang:如何解释类​​型声明效率?  [关闭]

问题描述:

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?

I can't quite figure out what's your main question, but I'll try to answer the ones you asked as best as I can.

It seems that the type assertion is slower than the pointer cast in C?

Yes, it is. Type assertions need to be safe at runtime, thus there is a number of checks they need to perform. It's even worse with interface-to-interface assertion, because you also need to ensure that the type implements the interface.

With that said, they can definitely perform better. In fact, here is comparison of your benchmark results on Go 1.4.2. vs latest dev version of Go 1.5:

  • Go 1.4.2: testE2I: 10.014922955s, testE2T: 4.465621814s

  • Go 1.5 dev: testE2I: 7.201485053s, testE2T: 287.08346ms

It's more than ten times faster now, and Go 1.6's new SSA backend might bring even better optimisations.

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?

My guess it that it's gccgo's lack of escape analysis, but I may be wrong. I was actually able to run the benchmark with gccgo on my machine, but it consumed about 9 GB of RAM, which is everything but normal. I'm pretty sure that filing an issue about that wouldn't hurt. Anyway, here are the results with -O3:

  • gccgo: testE2I: 30.405681s, testE2T: 1.734307s

Faster on the concrete type, but much slower with interface-to-interface assertion.