Skip to content

Instantly share code, notes, and snippets.

@jamband
Last active October 14, 2015 07:02
Show Gist options
  • Save jamband/e5c734b9e7b05fec6ca3 to your computer and use it in GitHub Desktop.
Save jamband/e5c734b9e7b05fec6ca3 to your computer and use it in GitHub Desktop.
Go: Benchmark of repeat and concatenation of characters
package s
import (
"bytes"
"testing"
)
func A1() (s string) {
for i := 0; i < 1000; i++ {
s += "a"
}
return
}
func A2() string {
var b bytes.Buffer
for i := 0; i < 1000; i++ {
b.WriteString("a")
}
return b.String()
}
func A3() string {
b := make([]byte, 1000)
bp := copy(b, "a")
for bp < len(b) {
copy(b[bp:], b[:bp])
bp *= 2
}
return string(b)
}
func BenchmarkA1(b *testing.B) {
for i := 0; i < b.N; i++ {
A1()
}
}
func BenchmarkA2(b *testing.B) {
for i := 0; i < b.N; i++ {
A2()
}
}
func BenchmarkA3(b *testing.B) {
for i := 0; i < b.N; i++ {
A3()
}
}
// BenchmarkA1-4 10000 244578 ns/op
// BenchmarkA2-4 100000 18698 ns/op
// BenchmarkA3-4 3000000 464 ns/op
// A3() == strings.Repeat()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment