Skip to content

Instantly share code, notes, and snippets.

@zimmski
Last active November 1, 2016 22:42
Show Gist options
  • Save zimmski/bdf2419c78b54abf944c145deb23d2b9 to your computer and use it in GitHub Desktop.
Save zimmski/bdf2419c78b54abf944c145deb23d2b9 to your computer and use it in GitHub Desktop.
Benchmark concatinating rune slices
package argh
import (
"testing"
"github.com/stretchr/testify/assert"
)
// $ go test -run=XXX -bench=.
// BenchmarkConcatAppendConcatOnce-4 5000000 262 ns/op
// BenchmarkConcatCopyConcatOnce-4 5000000 227 ns/op
// BenchmarkConcatAppendReuse-4 20000 82434 ns/op
// BenchmarkConcatCopyReuse-4 2000 1059490 ns/op
const repeat_concat = 100
var text1 = []rune("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut risus et enim consectetur convallis a non ipsum. Sed nec nibh cursus, interdum libero vel.")
var text1_1 = append(append([]rune{}, text1...), text1...)
func concat_append(r1, r2 []rune) []rune {
return append(r1, r2...)
}
func concat_copy(r1, r2 []rune) []rune {
result := make([]rune, len(r1)+len(r2))
copy(result, r1)
copy(result[len(r1):], r2)
return result
}
func TestConcatAppend(t *testing.T) {
assert.Equal(t, text1_1, concat_append(text1, text1))
}
func TestConcatCopy(t *testing.T) {
assert.Equal(t, text1_1, concat_copy(text1, text1))
}
var result []rune
func BenchmarkConcatAppendConcatOnce(b *testing.B) {
for n := 0; n < b.N; n++ {
var rs = []rune{}
result = concat_append(rs, text1)
}
}
func BenchmarkConcatCopyConcatOnce(b *testing.B) {
for n := 0; n < b.N; n++ {
var rs = []rune{}
result = concat_copy(rs, text1)
}
}
func BenchmarkConcatAppendReuse(b *testing.B) {
for n := 0; n < b.N; n++ {
var rs = []rune{}
for i := 0; i < repeat_concat; i++ {
rs = concat_append(rs, text1)
}
result = rs
}
}
func BenchmarkConcatCopyReuse(b *testing.B) {
for n := 0; n < b.N; n++ {
var rs = []rune{}
for i := 0; i < repeat_concat; i++ {
rs = concat_copy(rs, text1)
}
result = rs
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment