Created
April 9, 2020 00:48
-
-
Save C-Pro/6f67e89a6bb8c3c10c98fdd745a525c1 to your computer and use it in GitHub Desktop.
Benchmark for four types of string concatenation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$ 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