Last active
April 12, 2017 10:07
-
-
Save jehaby/db35f03df6e03854a1d737a826970c7f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
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