Go 中的类型断言和切换性能
在编程语言中,在运行时确定变量或对象的类型是一项基本操作。 Go 使用类型断言和类型开关来促进此过程。本文深入探讨了这些技术的性能特征。
性能问题
在某些语言(如 C/C)中,运行时类型发现可能会导致性能损失。 Go 程序员思考过类型断言或类型切换是否表现出类似的低效率。为了解决这个问题,让我们执行一个全面的基准测试:
package main import ( "fmt" "testing" ) 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") } }
示例代码使用类型开关来确定输入变量的类型为任何内容。
基准比较
进行了一系列基准测试,以比较类型断言和开关与直接方法调用和接口的性能实现:
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() } } }
在多个测试机器上,结果一致表明所有四种方法都以相似的速度执行:直接方法调用、接口实现、类型断言和类型切换。以下示例演示了这些发现:
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
因此,我们的结论是,与其他类型检查方法相比,Go 中的类型断言和类型切换不会导致明显的性能损失。
以上是与其他类型检查方法相比,Go 的类型断言和类型开关表现如何?的详细内容。更多信息请关注PHP中文网其他相关文章!