测试Go语言的interface的效率

interface是Go语言中的一大特点,甚至说是灵魂也不为过。

interface应该会在Go程序中大量出现和使用,因为有必要了解和测试下它的效率。


测试思路:

使用vector包,测试原生的IntVector和用interface包装后的vector的效率。

Go1中去掉了vector包,不过当时我把vector的代码保留了一份,微笑

在代码库里应该也能找到。我找到了一个版本的:https://code.google.com/p/go/source/browse?name=weekly.2011-08-17#hg%2Fsrc%2Fpkg%2Fcontainer%2Fvector

可能和我测试用的代码有差别,没仔细对比过,不过应该差不多。

Go语言中interface的实现:http://research.swtch.com/interfaces

据作者说一次函数调用要花5条CPU指令(C++的虚函数是3条)。

下面是测试代码:

package main

import (
	"fmt"
	"time"
	. "vector"
//	"vector/vector"
)

const size = 1000000

func testIntVectorPush() {
	v := make(IntVector, size)
	t0 := time.Now()
	for i := 1; i < size; i++ {
		v.Push(i)
	}
	t1 := time.Now()
	fmt.Printf("The testIntVectorPush call took %v to run.\n", t1.Sub(t0))
	v = nil
}

func testIntVectorAt() {
	v := make(IntVector, size)
	t0 := time.Now()
	for j := 0; j < 1000; j++ {
		for i := 1; i < size; i++ {
			v.At(i)
		}
	}
	t1 := time.Now()
	fmt.Printf("The testIntVectorAt call took %v to run.\n", t1.Sub(t0))
	v = nil
}

func testVectorPush() {
	v := make(Vector, size)
	t0 := time.Now()
	for i := 1; i < size; i++ {
		v.Push(i)
	}
	t1 := time.Now()
	fmt.Printf("The testVectorPush call took %v to run.\n", t1.Sub(t0))
	v = nil
}

func testVectorAt() {
	v := make(Vector, size)
	t0 := time.Now()
	for j := 0; j < 1000; j++ {
		for i := 1; i < size; i++ {
			v.At(i)
		}
	}

	t1 := time.Now()
	fmt.Printf("The testVectorAt call took %v to run.\n", t1.Sub(t0))
	v = nil
}

func main() {
	fmt.Println("abc")
	i := 0
	for ; i < size; i++ {
		i += i
	}
	fmt.Println(i)

	testIntVectorPush()
	testIntVectorPush()
	testVectorPush()
	testVectorPush()

	testIntVectorAt()
	testIntVectorAt()
	testVectorAt()
	testVectorAt()

}

测试结果:

The testIntVectorPush call took 19.0011ms to run.
The testIntVectorPush call took 19.0011ms to run.
The testVectorPush call took 64.0037ms to run.
The testVectorPush call took 51.0029ms to run.
The testIntVectorAt call took 1.2920739s to run.
The testIntVectorAt call took 1.2990743s to run.
The testVectorAt call took 2.4831421s to run.
The testVectorAt call took 2.5131438s to run.

明显地原生的IntVector比用interface包装过的Vector要快2到3倍。


总结:

Go语言中的interface很灵活,但是也付出了一定的性能代价。

如果是性能关键的代码,可以考虑放弃interface,自己写原生的代码。

话说回来,没有泛型机制,真的比较蛋疼,相当期待Go能支持泛型。

关于Go中的泛型,参见:泛型编程的困境



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值