高效地拼接字符串- go
对比结果:
BenchmarkAdd-4 36 31375864 ns/op 215482269 B/op 10005 allocs/op BenchmarkFmt-4 37 29228970 ns/op 159060782 B/op 30145 allocs/op BenchmarkJoin-4 15288 77334 ns/op 40960 B/op 1 allocs/op BenchmarkBuffer-4 18453 65148 ns/op 98240 B/op 11 allocs/op BenchmarkBuild-4 18283 63780 ns/op 154360 B/op 20 allocs/op PASS ok string 10.122s
代码:
package main import ( "bytes" "fmt" "strings" ) var stringArray []string func main() { // s := AddMethd() s := fmtMethod() fmt.Printf("%v\n", s) } func init() { setString(10000, "ABC") } func setString(n int, s string) { fmt.Println("执行初始化字符串数组") for i := 0; i <= n; i++ { stringArray = append(stringArray, s) } } func AddMethd() (s string) { for _, v := range stringArray { s += v + "," } return } func fmtMethod() (s string) { for _, v := range stringArray { s = fmt.Sprintf("%s%s", s, v) } return } func joinMethod() (s string) { s = strings.Join(stringArray, ",") return } func bufferMethod() (s string) { var b bytes.Buffer for _, v := range stringArray { b.WriteString(v) } s = b.String() return } func builderMethod() (s string) { var b strings.Builder for _, v := range stringArray { b.WriteString(v) } s = b.String() return }