dr637349 2015-07-23 03:10
浏览 33
已采纳

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?

  • 写回答

1条回答 默认 最新

  • du9698 2015-07-23 10:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!