Skip to content

Instantly share code, notes, and snippets.

@RickyS
Last active January 3, 2016 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RickyS/8463796 to your computer and use it in GitHub Desktop.
Save RickyS/8463796 to your computer and use it in GitHub Desktop.
Benchmark the Design of Append. Discussion in Golang group at: https://groups.google.com/forum/#!topic/golang-nuts/OHrLZU5SwAQ
package slicery
import ()
//const loops = 7
const elements = 6
const ints = 10000000 // smaller and less unrealistic
type X struct {
Data [ints]int
}
var slice []X
func initX(ptr *X, content int) {
for j := 0; j < ints; j++ {
ptr.Data[j] = content // First element has a different value for each array/slice.
content++
}
}
//////// Append technology
func Appender(loops int) {
for i := 0; i < loops; i++ {
slice = make([]X, 0, elements)
for j := 0; j < elements; j++ {
var x X
initX(&x, j)
slice = append(slice, x)
}
}
}
/////// Push technology
func push(slice []X) (nslice []X, nstruct *X) {
l := len(slice)
nslice = slice
if l == cap(slice) {
nslice = make([]X, l, cap(slice)*2)
copy(nslice, slice)
}
nslice = nslice[0 : l+1]
return nslice, &nslice[l]
}
func Pusher(loops int) {
for i := 0; i < loops; i++ {
slice = make([]X, 0, elements)
for j := 0; j < elements; j++ {
var px *X
slice, px = push(slice)
initX(px, j)
}
}
}
package slicery
import (
"testing"
)
func TestA(t *testing.T) {
Appender(3)
}
func TestP(t *testing.T) {
Pusher(3)
}
/////
func BenchmarkAppend(b *testing.B) {
Appender(b.N)
}
func BenchmarkPush(b *testing.B) {
Pusher(b.N)
}
@RickyS
Copy link
Author

RickyS commented Jan 16, 2014

Those benchmarks were run on an Intel i3 with 6 gigs of ram on Ubuntu 13.10, 64-bit. Go 1.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment