Created
April 29, 2019 01:54
-
-
Save haozibi/18f1e7ed80e067402cb60c79933aa1f7 to your computer and use it in GitHub Desktop.
string 连接基准测试
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 test | |
import ( | |
"fmt" | |
"strconv" | |
"testing" | |
) | |
const ( | |
str = "abc" | |
sep = "123" | |
intA int = 123456 | |
intB int64 = 1098765 | |
) | |
func BenchmarkFmtreflect(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = fmt.Sprintf("%v%v%v%v%v%v", str, str, str, sep, sep, sep) | |
} | |
} | |
// string fmt 连接,只含 string | |
func BenchmarkFmt(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = fmt.Sprintf("%s%s%s%s%s%s", str, str, str, sep, sep, sep) | |
} | |
} | |
// string + 连接,只含 string | |
func BenchmarkPlus(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = str + str + str + sep + sep + sep | |
} | |
} | |
func BenchmarkFmtWithInt(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = fmt.Sprintf("%d%s%s%s%s%d", intA, str, str, sep, sep, intB) | |
} | |
} | |
// string + 连接带数字 | |
func BenchmarkPlusWithInt(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = strconv.Itoa(intA) + str + str + sep + sep + strconv.FormatInt(intB, 10) | |
} | |
} | |
// goos: darwin | |
// goarch: amd64 | |
// pkg: xx | |
// BenchmarkFmtreflect-4 5000000 275 ns/op 32 B/op 1 allocs/op | |
// BenchmarkFmt-4 5000000 276 ns/op 32 B/op 1 allocs/op | |
// BenchmarkPlus-4 2000000000 0.35 ns/op 0 B/op 0 allocs/op | |
// BenchmarkFmtWithInt-4 5000000 305 ns/op 32 B/op 1 allocs/op | |
// BenchmarkPlusWithInt-4 10000000 133 ns/op 16 B/op 2 allocs/op | |
// PASS | |
// coverage: 0.0% of statements | |
// ok xx 7.491s | |
// Success: Benchmarks passed. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment