杨魅力
您可以使用,这更有效,请尝试以下操作:strings.Builderfunc buildString(a []string) string { var sb strings.Builder for i, s := range a { sb.WriteString(strconv.Itoa(i)) sb.WriteString(" === ") sb.WriteString(s) sb.WriteRune('\n') } return sb.String()}基准:Benchmark1-8 4203799 252 ns/op 56 B/op 3 allocs/opBenchmark6-8 5044305 280 ns/op 56 B/op 3 allocs/opBenchmark4-8 4332459 319 ns/op 72 B/op 3 allocs/opBenchmark5-8 2792514 371 ns/op 56 B/op 3 allocs/opBenchmark3-8 1000000 1018 ns/op 144 B/op 8 allocs/opBenchmark2-8 1000000 1109 ns/op 152 B/op 8 allocs/op法典:package mainimport ( "fmt" "strconv" "strings" "testing")func buildString(a []string) string { var sb strings.Builder for i, s := range a { sb.WriteString(strconv.Itoa(i)) sb.WriteString(" === ") sb.WriteString(s) sb.WriteRune('\n') } return sb.String()}func buildString6(a []string) string { var sb strings.Builder for i, s := range a { sb.WriteString(strconv.Itoa(i)) sb.WriteString(" === ") sb.WriteString(s) sb.WriteString("\n") } return sb.String()}func buildString5(a []string) string { var sb strings.Builder for i, s := range a { sb.WriteString(strconv.Itoa(i)) sb.WriteString(" === " + s + "\n") } return sb.String()}func buildString4(a []string) string { var sb strings.Builder b := make([]byte, 0, 10) for i, s := range a { b = strconv.AppendInt(b[:0], int64(i), 10) b = append(b, " === "...) b = append(b, s...) b = append(b, '\n') sb.WriteString(string(b)) } return sb.String()}func buildString3(a []string) string { var sb strings.Builder for i, s := range a { sb.WriteString(fmt.Sprintf("%d === %s\n", i, s)) } return sb.String()}func buildString2(strSlice []string) string { var bigString string for index, element := range strSlice { bigString += fmt.Sprintf("%d === %s\n", index, element) } return bigString}func Benchmark1(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString(strSlice) }}func Benchmark2(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString2(strSlice) }}func Benchmark3(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString3(strSlice) }}func Benchmark4(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString4(strSlice) }}func Benchmark5(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString5(strSlice) }}func Benchmark6(b *testing.B) { strSlice := []string{"one", "two", "three"} for i := 0; i < b.N; i++ { _ = buildString6(strSlice) }}go 版本 go1.17.1