Skip to content

Instantly share code, notes, and snippets.

@losinggeneration
Created June 30, 2020 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save losinggeneration/ceab078de814fc1f97a82d8947c4023a to your computer and use it in GitHub Desktop.
Save losinggeneration/ceab078de814fc1f97a82d8947c4023a to your computer and use it in GitHub Desktop.
String += within a loop issue
goos: linux
goarch: amd64
BenchmarkStringPlus-8 77480 132547 ns/op 1205014 B/op 1 allocs/op
BenchmarkStringPlusFmt-8 63650 124560 ns/op 1203372 B/op 3 allocs/op
BenchmarkStringBuilder-8 51845487 77.0 ns/op 185 B/op 0 allocs/op
BenchmarkStringBuilderFmt-8 7772652 146 ns/op 216 B/op 1 allocs/op
goos: linux
goarch: amd64
BenchmarkStringPlus-8 10000 1719950 ns/op 15540847 B/op 10 allocs/op
BenchmarkStringPlusFmt-8 10000 1854548 ns/op 18437905 B/op 38 allocs/op
BenchmarkStringBuilder-8 5278312 740 ns/op 1826 B/op 0 allocs/op
BenchmarkStringBuilderFmt-8 678554 1819 ns/op 2462 B/op 10 allocs/op
goos: linux
goarch: amd64
BenchmarkStringPlus-8 763 12973097 ns/op 118672419 B/op 107 allocs/op
BenchmarkStringPlusFmt-8 654 11944269 ns/op 117130386 B/op 373 allocs/op
BenchmarkStringBuilder-8 508676 4320 ns/op 18949 B/op 0 allocs/op
BenchmarkStringBuilderFmt-8 81718 14272 ns/op 20585 B/op 99 allocs/op
goos: linux
goarch: amd64
BenchmarkStringPlus-8 100 170073279 ns/op 1554084884 B/op 1079 allocs/op
BenchmarkStringPlusFmt-8 100 173231980 ns/op 1744877880 B/op 3837 allocs/op
BenchmarkStringBuilder-8 58435 44040 ns/op 164958 B/op 0 allocs/op
BenchmarkStringBuilderFmt-8 7850 142764 ns/op 213962 B/op 999 allocs/op
// Run benchmarks to showw the difference between string += and the string builder inside a loop. This also shows the
// minimal impact of fmt.Sprintf in comparison to using +=
package main
import (
"fmt"
"strings"
"testing"
)
// this is adjusted for each run
const scale = 1
func BenchmarkStringPlus(b *testing.B) {
var str string
for i := 0; i < b.N; i++ {
for n := 0; n < scale; n++ {
str += "Benchmarking string and builder"
}
}
}
func BenchmarkStringPlusFmt(b *testing.B) {
var str string
for i := 0; i < b.N; i++ {
for n := 0; n < scale; n++ {
str += fmt.Sprintf("Benchmarking string and builder: %d", i)
}
}
}
func BenchmarkStringBuilder(b *testing.B) {
var str strings.Builder
for i := 0; i < b.N; i++ {
for n := 0; n < scale; n++ {
str.WriteString("Benchmarking string and builder")
}
}
}
func BenchmarkStringBuilderFmt(b *testing.B) {
var str strings.Builder
for i := 0; i < b.N; i++ {
for n := 0; n < scale; n++ {
fmt.Fprintf(&str, "Benchmarking string and builder: %d", i)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment