Last active
January 3, 2016 12:38
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Those benchmarks were run on an Intel i3 with 6 gigs of ram on Ubuntu 13.10, 64-bit. Go 1.2.