Created
December 19, 2015 18:48
-
-
Save mark-rushakoff/1c4c9123a840be787e38 to your computer and use it in GitHub Desktop.
Which is faster: `s += str` or `buf.WriteString(str) ... buf.String()`?
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
PASS | |
BenchmarkStringConcat-4 2000000 3901 ns/op | |
BenchmarkByteBuffer-4 10000000 966 ns/op |
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
package strings_test | |
import ( | |
"bytes" | |
"testing" | |
) | |
import "strings" | |
var alphabet = strings.Split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "") | |
var result string | |
func TestNothing(t *testing.T) {} | |
func BenchmarkStringConcat(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
s := "" | |
for _, c := range alphabet { | |
s += c | |
} | |
result = s | |
} | |
if result != strings.Join(alphabet, "") { | |
b.Fatalf("bug") | |
} | |
} | |
func BenchmarkByteBuffer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
var b bytes.Buffer | |
for _, c := range alphabet { | |
_, _ = b.WriteString(c) | |
} | |
result = b.String() | |
} | |
if result != strings.Join(alphabet, "") { | |
b.Fatalf("bug") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment