Created
October 23, 2018 07:30
-
-
Save khanhtc1202/f68ec3bf0f90633c3271466cf90fb199 to your computer and use it in GitHub Desktop.
String concatenate
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 ( | |
"bytes" | |
"strings" | |
"testing" | |
) | |
func BenchmarkConcat(b *testing.B) { | |
var str string | |
for n := 0; n < b.N; n++ { | |
str += "x" | |
} | |
b.StopTimer() | |
if s := strings.Repeat("x", b.N); str != s { | |
b.Errorf("unexpected result; got=%s, want=%s", str, s) | |
} | |
} | |
func BenchmarkBuffer(b *testing.B) { | |
var buffer bytes.Buffer | |
for n := 0; n < b.N; n++ { | |
buffer.WriteString("x") | |
} | |
b.StopTimer() | |
if s := strings.Repeat("x", b.N); buffer.String() != s { | |
b.Errorf("unexpected result; got=%s, want=%s", buffer.String(), s) | |
} | |
} | |
func BenchmarkCopy(b *testing.B) { | |
bs := make([]byte, b.N) | |
bl := 0 | |
b.ResetTimer() | |
for n := 0; n < b.N; n++ { | |
bl += copy(bs[bl:], "x") | |
} | |
b.StopTimer() | |
if s := strings.Repeat("x", b.N); string(bs) != s { | |
b.Errorf("unexpected result; got=%s, want=%s", string(bs), s) | |
} | |
} | |
// Go 1.10 | |
func BenchmarkStringBuilder(b *testing.B) { | |
var strBuilder strings.Builder | |
b.ResetTimer() | |
for n := 0; n < b.N; n++ { | |
strBuilder.WriteString("x") | |
} | |
b.StopTimer() | |
if s := strings.Repeat("x", b.N); strBuilder.String() != s { | |
b.Errorf("unexpected result; got=%s, want=%s", strBuilder.String(), s) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment