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中的泛型,参见:泛型编程的困境