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 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line