Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Focinfi/af4aafd437eac1aa2885464f22ef7aa8 to your computer and use it in GitHub Desktop.
Save Focinfi/af4aafd437eac1aa2885464f22ef7aa8 to your computer and use it in GitHub Desktop.
benchmark for strings.Join and string appending
package main
import (
"strconv"
"strings"
"testing"
)
const sliceLen = 1000
func buildWithStringsJion() string {
l := make([]string, sliceLen, sliceLen)
for i := 0; i < 1000; i++ {
l[i] = strconv.Itoa(i)
}
return strings.Join(l, ",")
}
func buildWithStringAppending() string {
s := ""
for i := 0; i < 1000; i++ {
if i == 0 {
s = strconv.Itoa(i)
} else {
s += "," + strconv.Itoa(i)
}
}
return s
}
func BenchmarkBuildWithStringsJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
buildWithStringsJion()
}
}
func BenchmarkBuildWithStringAppending(b *testing.B) {
for i := 0; i < b.N; i++ {
buildWithStringAppending()
}
}
// $go test -bench . -benchmem
// output #=>
// goos: darwin
// goarch: amd64
// pkg: github.com/Focinfi/GolangPractices/learn-awesome-project/strings
// BenchmarkBuildWithStringsJoin-4 50000 37925 ns/op 11072 B/op 902 allocs/op
// BenchmarkBuildWithStringAppending-4 5000 309293 ns/op 2033473 B/op 1899 allocs/op
// PASS
// ok github.com/Focinfi/GolangPractices/learn-awesome-project/strings 3.870s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment