Created
March 19, 2018 06:15
-
-
Save barryz/0f34729dfdacc2d2a2765e38d263bdeb 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
package main | |
import ( | |
"bytes" | |
"strings" | |
"testing" | |
) | |
func BenchmarkStringBuilder(b *testing.B) { | |
var bi strings.Builder | |
b.ResetTimer() | |
for i := 1; i < b.N; i++ { | |
bi.WriteString("hello") | |
bi.WriteString("world") | |
bi.WriteString("-Go 1.10") | |
_ = bi.String() | |
} | |
b.StopTimer() | |
} | |
func BenchmarkBytesBuffer(b *testing.B) { | |
var bi bytes.Buffer | |
b.ResetTimer() | |
for i := 1; i < b.N; i++ { | |
bi.WriteString("hello") | |
bi.WriteString("world") | |
bi.WriteString("-Go 1.10") | |
_ = bi.String() | |
} | |
b.StopTimer() | |
} | |
func BenchmarkStringConcat(b *testing.B) { | |
var a string | |
b.ResetTimer() | |
for i := 1; i < b.N; i++ { | |
a += "helloworld-Go 1.10" | |
_ = a | |
} | |
b.StopTimer() | |
} | |
func BenchmarkStringCopy(b *testing.B) { | |
// 需要提前知道容量 | |
bs := make([]byte, b.N) | |
bl := 0 | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
bl += copy(bs[bl:], "helloworld-Go 1.10") | |
_ = string(bs) | |
} | |
b.StopTimer() | |
} |
Author
barryz
commented
Mar 19, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment