Skip to content

Instantly share code, notes, and snippets.

@DaidoujiChen
Last active August 31, 2017 09:28
Show Gist options
  • Save DaidoujiChen/8af0e6f0bbd84fa52a9ae3d884c8122c to your computer and use it in GitHub Desktop.
Save DaidoujiChen/8af0e6f0bbd84fa52a9ae3d884c8122c to your computer and use it in GitHub Desktop.
Golang String 串接 PK 戰 - Golang String Concat / Buffer / Join / Copy / Append Performance Comparison
package main
import (
"bytes"
"fmt"
"strconv"
"strings"
"testing"
)
// test only benchmarks use "go test -bench . -run=^$"
/* Result in My Macbook 2.7g i5
BenchmarkConcat-4 1000000 85240 ns/op
BenchmarkBuffer-4 100000000 13.8 ns/op
BenchmarkJoin-4 5000000 235 ns/op
BenchmarkCopy-4 300000000 4.81 ns/op
BenchmarkAppend-4 300000000 4.81 ns/op
*/
func TestCopy(t *testing.T) {
bs := []byte{}
for n := 0; n < 10; n++ {
app := []byte{strconv.Itoa(n)[0]}
bs = append(bs, app...)
}
fmt.Println(string(bs))
}
func BenchmarkConcat(b *testing.B) {
var str string
x := "x"
for n := 0; n < b.N; n++ {
str += x
}
}
func BenchmarkBuffer(b *testing.B) {
var buffer bytes.Buffer
x := "x"
for n := 0; n < b.N; n++ {
buffer.WriteString(x)
}
_ = buffer.String()
}
func BenchmarkJoin(b *testing.B) {
s := []string{}
x := "x"
for n := 0; n < b.N; n++ {
s = append(s, x)
}
_ = strings.Join(s, "")
}
// Limit Length
func BenchmarkCopy(b *testing.B) {
bs := make([]byte, b.N)
bl := 0
x := "x"
for n := 0; n < b.N; n++ {
bl += copy(bs[bl:], x)
}
_ = string(bs)
}
// Dynamic Length
func BenchmarkAppend(b *testing.B) {
bs := []byte{}
x := "x"
for n := 0; n < b.N; n++ {
bs = append(bs, x...)
}
_ = string(bs)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment