Skip to content

Instantly share code, notes, and snippets.

@jehaby
Last active April 12, 2017 10:07
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 jehaby/db35f03df6e03854a1d737a826970c7f to your computer and use it in GitHub Desktop.
Save jehaby/db35f03df6e03854a1d737a826970c7f to your computer and use it in GitHub Desktop.
/*
go test str_conc_test.go -bench . -benchtime 10s
BenchmarkConcatOne-4 2000000 7684 ns/op
BenchmarkConcatTwo-4 5000000 2883 ns/op
BenchmarkConcatThree-4 5000000 2933 ns/op
PASS
ok command-line-arguments 56.982s
*/
package main
import (
"bytes"
"strconv"
"testing"
)
var ids = []int{30028, 300300, 200200, 123928, 89282, 832892, 238983, 30028, 300300, 200200, 123928, 89282, 832892, 238983, 30028, 300300, 200200, 123928, 89282, 832892, 238983, 30028, 300300, 200200, 123928, 89282, 832892, 238983}
func BenchmarkConcatOne(b *testing.B) {
for i := 0; i < b.N; i++ {
concatOne(ids)
}
}
func BenchmarkConcatTwo(b *testing.B) {
for i := 0; i < b.N; i++ {
concatTwo(ids)
}
}
func BenchmarkConcatThree(b *testing.B) {
for i := 0; i < b.N; i++ {
concatThree(ids)
}
}
func concatOne(ids []int) string {
res := ""
for _, id := range ids {
if len(res) > 0 {
res += ","
}
res += strconv.Itoa(id)
}
return res
}
const averageIdLen = 6
func concatTwo(ids []int) string {
buf := bytes.NewBuffer(make([]byte, 0, (averageIdLen+1)*len(ids)))
for _, id := range ids {
if buf.Len() > 0 {
buf.WriteString(",")
}
buf.WriteString(strconv.Itoa(id))
}
return buf.String()
}
func concatThree(ids []int) string {
buf := bytes.NewBuffer(make([]byte, 0, (averageIdLen+1)*len(ids)))
comma := ","
for _, id := range ids {
if buf.Len() > 0 {
buf.WriteString(comma)
}
buf.WriteString(strconv.Itoa(id))
}
return buf.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment