Skip to content

Instantly share code, notes, and snippets.

@pohzipohzi
Forked from dtjm/join_test.go
Created December 14, 2018 08:02
Show Gist options
  • Save pohzipohzi/e57ea0dd6956eb63878b1966fdd68099 to your computer and use it in GitHub Desktop.
Save pohzipohzi/e57ea0dd6956eb63878b1966fdd68099 to your computer and use it in GitHub Desktop.
strings.Join vs fmt.Sprintf vs string concat (+)
package join
import (
"fmt"
"strings"
"testing"
)
var (
testData = []string{"a", "b", "c", "d", "e"}
)
func BenchmarkJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
s := strings.Join(testData, ":")
_ = s
}
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
s := fmt.Sprintf("%s:%s:%s:%s:%s", testData[0], testData[1], testData[2], testData[3], testData[4])
_ = s
}
}
func BenchmarkConcat(b *testing.B) {
for i := 0; i < b.N; i++ {
s := testData[0] + ":" + testData[1] + ":" + testData[2] + ":" + testData[3] + ":" + testData[4]
_ = s
}
}
@pohzipohzi
Copy link
Author

Test results on MacBook Pro (awesomeProject is the default name for a new Goland project)

goos: darwin
goarch: amd64
pkg: awesomeProject/join
BenchmarkJoin-8         20000000                94.3 ns/op
BenchmarkSprintf-8       5000000               375 ns/op
BenchmarkConcat-8       20000000                67.5 ns/op
PASS
ok      awesomeProject/join     5.667s

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