Skip to content

Instantly share code, notes, and snippets.

@C-Pro
Created April 9, 2020 00:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save C-Pro/6f67e89a6bb8c3c10c98fdd745a525c1 to your computer and use it in GitHub Desktop.
Save C-Pro/6f67e89a6bb8c3c10c98fdd745a525c1 to your computer and use it in GitHub Desktop.
Benchmark for four types of string concatenation
package concatbench
import (
"fmt"
"strings"
"testing"
)
const (
s1 = "четёре чёрненьких чумазеньких чертёнка, "
s2 = "чертили чёрными чернилами чертёж, "
)
func BenchmarkPlus(b *testing.B) {
s := s1
for i := 0; i < b.N; i++ {
s = s + s2
}
_ = s
}
func BenchmarkSprintf(b *testing.B) {
s := s1
for i := 0; i < b.N; i++ {
s = fmt.Sprintf("%s%s", s, s2)
}
_ = s
}
func BenchmarkAppend(b *testing.B) {
l := []rune(s1)
for i := 0; i < b.N; i++ {
l = append(l, []rune(s2)...)
}
_ = string(l)
}
func BenchmarkBuilder(b *testing.B) {
var sb strings.Builder
sb.WriteString(s1)
for i := 0; i < b.N; i++ {
sb.WriteString(s2)
}
_ = sb.String()
}
@C-Pro
Copy link
Author

C-Pro commented Apr 9, 2020

$ go test -benchmem -bench=.
goos: linux
goarch: amd64
BenchmarkPlus-8      	   29947	    129963 ns/op	  947487 B/op	       1 allocs/op
BenchmarkSprintf-8   	   14324	    126644 ns/op	  912833 B/op	       4 allocs/op
BenchmarkAppend-8    	 1995886	       563 ns/op	     873 B/op	       0 allocs/op
BenchmarkBuilder-8   	23572284	        53.2 ns/op	     327 B/op	       0 allocs/op
PASS
ok  	_/home/cpro/work/temp/build	10.010s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment