Skip to content

Instantly share code, notes, and snippets.

@kvannotten
Created May 8, 2018 09:30
Show Gist options
  • Save kvannotten/bb56cf7b208dbb0f26eacdee3fd8eca2 to your computer and use it in GitHub Desktop.
Save kvannotten/bb56cf7b208dbb0f26eacdee3fd8eca2 to your computer and use it in GitHub Desktop.
Test golang string concat
package main
import (
"bytes"
"fmt"
"strings"
)
func main() {
}
func concatSprintf(one, two string) string {
return fmt.Sprintf("%s%s", one, two)
}
func concatPlus(one, two string) string {
return one + two
}
func concatBytes(one, two string) string {
var buf bytes.Buffer
buf.WriteString(one)
buf.WriteString(two)
return buf.String()
}
func concatBuilder(one, two string) string {
var buf strings.Builder
buf.WriteString(one)
buf.WriteString(two)
return buf.String()
}
package main
import "testing"
func BenchmarkConcatSprintf(b *testing.B) {
for n := 0; n < b.N; n++ {
concatSprintf(string(n), string(n+1))
}
}
func BenchmarkConcatPlus(b *testing.B) {
for n := 0; n < b.N; n++ {
concatPlus(string(n), string(n+1))
}
}
func BenchmarkConcatBytes(b *testing.B) {
for n := 0; n < b.N; n++ {
concatBytes(string(n), string(n+1))
}
}
func BenchmarkConcatBuilder(b *testing.B) {
for n := 0; n < b.N; n++ {
concatBuilder(string(n), string(n+1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment