Created
February 10, 2018 09:15
-
-
Save Focinfi/f89a14913740a4c9f272d0000a9be36e to your computer and use it in GitHub Desktop.
benchmark for strings.Join and string appending
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 main | |
import ( | |
"strconv" | |
"strings" | |
"testing" | |
) | |
const sliceLen = 1000 | |
func buildWithStringsJion() string { | |
l := make([]string, sliceLen, sliceLen) | |
for i := 0; i < 1000; i++ { | |
l[i] = strconv.Itoa(i) | |
} | |
return strings.Join(l, ",") | |
} | |
func buildWithStringAppending() string { | |
s := "" | |
for i := 0; i < 1000; i++ { | |
if i == 0 { | |
s = strconv.Itoa(i) | |
} else { | |
s += "," + strconv.Itoa(i) | |
} | |
} | |
return s | |
} | |
func BenchmarkBuildWithStringsJoin(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
buildWithStringsJion() | |
} | |
} | |
func BenchmarkBuildWithStringAppending(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
buildWithStringAppending() | |
} | |
} | |
// $go test -bench . -benchmem | |
// output #=> | |
// goos: darwin | |
// goarch: amd64 | |
// pkg: github.com/Focinfi/GolangPractices/learn-awesome-project/strings | |
// BenchmarkBuildWithStringsJoin-4 50000 37925 ns/op 11072 B/op 902 allocs/op | |
// BenchmarkBuildWithStringAppending-4 5000 309293 ns/op 2033473 B/op 1899 allocs/op | |
// PASS | |
// ok github.com/Focinfi/GolangPractices/learn-awesome-project/strings 3.870s | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment