Skip to content

Instantly share code, notes, and snippets.

@phemmer
Created February 25, 2015 14:31
Show Gist options
  • Save phemmer/d9e18ec78f7ad2dbec0f to your computer and use it in GitHub Desktop.
Save phemmer/d9e18ec78f7ad2dbec0f to your computer and use it in GitHub Desktop.
string concat benchmark
package main
import (
"fmt"
"testing"
)
const str = "s"
var bslice = []byte(str)
func BenchmarkByteSliceGrow(b *testing.B) {
var bs []byte
for n := 0; n < b.N; n++ {
bs = append(bs, bslice...)
}
}
func BenchmarkStringConcatGrow(b *testing.B) {
strAppend := ""
for n := 0; n < b.N; n++ {
strAppend += str
}
}
func BenchmarkFmtSprintfGrow(b *testing.B) {
strFmt := ""
for n := 0; n < b.N; n++ {
strFmt = fmt.Sprintf("%s%s", strFmt, str)
}
}
func BenchmarkByteSliceDiscard(b *testing.B) {
var bs []byte
for n := 0; n < b.N; n++ {
_ = append(bs, bslice...)
}
}
func BenchmarkStringConcatDiscard(b *testing.B) {
strAppend := ""
for n := 0; n < b.N; n++ {
_ = strAppend + str
}
}
func BenchmarkFmtSprintfDiscard(b *testing.B) {
strFmt := ""
for n := 0; n < b.N; n++ {
_ = fmt.Sprintf("%s%s", strFmt, str)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment