Please consider these two snippets in GO and C++11. In C++ std::vector
is a doubling-array which has amortized O(1) insert operation. How to achieve the same performance in GO? Problem is that this GO code is about 3 times slower on my hardware. Run many times.
Compiled:
-
go build vec.go
(go version go1.2.1 linux/amd64) -
g++ -O2 -std=gnu++11 -o vec vec.cc
(g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2)
GO version (vec.go):
package main
type X struct {
x int32
y float64
}
const N int = 80000000
func main() {
x := X{123, 2.64}
s := make([]X, 1)
for i := 0; i < N; i++ {
s = append(s, x)
}
}
C++11 version (vec.cc):
#include <vector>
const int N = 80000000;
struct X {
int x;
double y;
};
int main(void)
{
X x{123, 2.64};
std::vector<X> s(1);
for (int i = 0; i < N; ++i) {
s.push_back(x);
}
}