string连接效率比较
方法
- +=
- fmt.Springf
- buffer.WriteString
- builder.WriteString
- append
代码
func main() {
// 1. +=
str := "test"
name := "zh"
s := time.Now()
for i := 0; i < 100000; i++ {
str += name
}
e := time.Since(s)
fmt.Println("+=: time cost:", e)
// 2. fmt.Sprintf
str = "test"
name = "zh"
s = time.Now()
for i := 0; i < 100000; i++ {
str = fmt.Sprintf("%s%s", str, name)
}
e = time.Since(s)
fmt.Println("fmt.Sprintf time cost:", e)
// 3. buffer.WriteString
str = "test"
name = "zh"
var buffer = bytes.Buffer{}
s = time.Now()
buffer.WriteString(str)
for i := 0; i < 100000; i++ {
buffer.WriteString(name)
}
e = time.Since(s)
fmt.Println("buffer.WriteString time cost:", e)
// 4. builder.WriteString
str = "test"
name = "zh"
var builder = strings.Builder{}
s = time.Now()
builder.WriteString(str)
for i := 0; i < 100000; i++ {
builder.WriteString(name)
}
e = time.Since(s)
fmt.Println("builder.WriteString time cost:", e)
// 5. append
str = "test"
name = "zh"
s = time.Now()
bstr := []byte(str)
bname := []byte(name)
for i := 0; i < 100000; i++ {
bstr = append(bstr, bname...)
}
e = time.Since(s)
fmt.Println("append time cost:", e)
}
结果
+=: time cost: 1.3233293s
fmt.Sprintf time cost: 2.6775514s
buffer.WriteString time cost: 519.2µs
builder.WriteString time cost: 518.1µs
append time cost: 503.6µs
总结
以上结果是在自己电脑上跑的,仅供参考
append, strings.builder 效率高