本次测试为并发连续拼接,拼接逻辑如下
拼接次数:loop = 5
拼接循环体:hello
3次拼接后结果:hellohellohellohellohello
package main
import (
"bytes"
"fmt"
"strings"
"time"
)
var loop = 100000
func main() {
var s string
var start time.Time
concatStr := "hello"
fmt.Println("loop:", loop)
s = ""
// 加号'+' 连接
start = time.Now()
for i := 0; i < loop; i++ {
s += concatStr
}
//fmt.Println(s)
fmt.Println("+连接方法:", time.Since(start))
s = ""
// append 连接
start = time.Now()
for i := 0; i < loop; i++ {
s = string(append([]byte(s), concatStr...))
}
//fmt.Println(s)
fmt.Println("append方法:", time.Since(start))
s = ""
// bytes.WriteString 方法
start = time.Now()
for i := 0; i < loop; i++ {
var buf bytes.Buffer
buf.WriteString(s)
buf.WriteString(concatStr)
s = buf.String()
}
//fmt.Println(s)
fmt.Println("bytes.WriteString 方法", time.Since(start))
s = ""
// fmt 方法连接
start = time.Now()
for i := 0; i < loop; i++ {
s = fmt.Sprintf("%s%s", s, concatStr)
}
//fmt.Println(s)
fmt.Println("fmt 方法:", time.Since(start))
if loop < 10000 {
s = ""
var v []string
for i := 0; i < loop; i++ {
v = append(v, concatStr)
}
// join 方法连接
start = time.Now()
for i := 0; i < loop; i++ {
s = strings.Join(v, "")
}
//fmt.Println(s)
fmt.Println("strings.Join 方法", time.Since(start))
}
}
输出结果
loop: 10
+连接方法: 8.79µs
append方法: 1.416µs
bytes.WriteString 方法 1.966µs
fmt 方法: 6.754µs
strings.Join 方法 2.431µs
append > bytes.WriteString > strings.Join > fmt > +
loop: 100
+ 连接方法: 93.558µs
append 方法: 127.425µs
bytes.WriteString 方法 115.45µs
fmt 方法: 78.906µs
strings.Join 方法 183.917µs
fmt > + > bytes.WriteString > append > strings.Join
loop: 1000
+连接方法: 3.365524ms
append方法: 2.572024ms
bytes.WriteString 方法 1.902682ms
fmt 方法: 1.149722ms
strings.Join 方法 18.767488ms
fmt > bytes.WriteString > append > + > strings.Join
fmt > bytes.WriteString > append > + > strings.Join
loop: 10000
+ 连接方法: 71.836577ms
append 方法: 142.325765ms
bytes.WriteString 方法 251.774228ms
fmt 方法: 91.319374ms
strings.Join 方法 1.314004829s
+ > fmt > append > bytes.WriteString > strings.Join
loop: 100000
+ 连接方法: 5.812739022s
append 方法: 9.705128127s
bytes.WriteString 方法 9.678353962s
fmt 方法: 9.577834615s
strings.Join 方法 2m37.173384017s
+ > fmt ~ bytes.WriteString ~ append > strings.Join
效率排序:
+ > fmt ~ bytes.WriteString ~ append > strings.Join