gpt4 book ai didi

casting - 类型断言/类型切换是否性能不佳/在 Go 中很慢?

转载 作者:IT老高 更新时间:2023-10-28 12:59:35 28 4
gpt4 key购买 nike

在 Go 中使用类型断言/类型切换作为运行时类型发现的方法有多慢?

我听说例如在 C/C++ 中,在运行时发现类型的性能很差。为了绕过这一点,您通常将类型成员添加到类中,这样您就可以与这些成员进行比较而不是强制转换。

我在整个 www 中都没有找到明确的答案。

这是我要问的一个示例 - 与其他类型检查方法(如上面提到的或我不知道的其他方法)相比,这是否被认为 快速

func question(anything interface{}) {
switch v := anything.(type) {
case string:
fmt.Println(v)
case int32, int64:
fmt.Println(v)
case SomeCustomType:
fmt.Println(v)
default:
fmt.Println("unknown")
}
}

最佳答案

编写一个基准测试来检查它很容易:http://play.golang.org/p/E9H_4K2J9-

package main

import (
"testing"
)

type myint int64

type Inccer interface {
inc()
}

func (i *myint) inc() {
*i = *i + 1
}

func BenchmarkIntmethod(b *testing.B) {
i := new(myint)
incnIntmethod(i, b.N)
}

func BenchmarkInterface(b *testing.B) {
i := new(myint)
incnInterface(i, b.N)
}

func BenchmarkTypeSwitch(b *testing.B) {
i := new(myint)
incnSwitch(i, b.N)
}

func BenchmarkTypeAssertion(b *testing.B) {
i := new(myint)
incnAssertion(i, b.N)
}

func incnIntmethod(i *myint, n int) {
for k := 0; k < n; k++ {
i.inc()
}
}

func incnInterface(any Inccer, n int) {
for k := 0; k < n; k++ {
any.inc()
}
}

func incnSwitch(any Inccer, n int) {
for k := 0; k < n; k++ {
switch v := any.(type) {
case *myint:
v.inc()
}
}
}

func incnAssertion(any Inccer, n int) {
for k := 0; k < n; k++ {
if newint, ok := any.(*myint); ok {
newint.inc()
}
}
}

2019 年 10 月 9 日编辑

上面展示的方法似乎是相同的,彼此之间没有优势。以下是我机器上的结果(AMD R7 2700X,Golang v1.12.9):

BenchmarkIntmethod-16           2000000000           1.67 ns/op
BenchmarkInterface-16 1000000000 2.03 ns/op
BenchmarkTypeSwitch-16 2000000000 1.70 ns/op
BenchmarkTypeAssertion-16 2000000000 1.67 ns/op
PASS

再次:

BenchmarkIntmethod-16           2000000000           1.68 ns/op
BenchmarkInterface-16 1000000000 2.01 ns/op
BenchmarkTypeSwitch-16 2000000000 1.66 ns/op
BenchmarkTypeAssertion-16 2000000000 1.67 ns/op

2015 年 1 月 19 日的先前结果

在我的 amd64 机器上,我得到以下时间:

$ go test -bench=.
BenchmarkIntmethod 1000000000 2.71 ns/op
BenchmarkInterface 1000000000 2.98 ns/op
BenchmarkTypeSwitch 100000000 16.7 ns/op
BenchmarkTypeAssertion 100000000 13.8 ns/op

所以看起来通过类型切换或类型断言访问方法比直接或通过接口(interface)调用方法慢大约 5-6 倍。

我不知道 C++ 是否较慢,或者您的应用程序是否可以容忍这种减速。

关于casting - 类型断言/类型切换是否性能不佳/在 Go 中很慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28024884/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com