原文地址:https://www.douyacun.com/article/64bf57a2d3099acbb960ca561d225628
+
拼接 最慢 少量比较推荐strings.join
拼接 其次-推荐buffers.NewBufferString
拼接 最快,需要自己实现package main
import (
"bytes"
"fmt"
"strconv"
"strings"
"sync"
"time"
"unsafe"
)
func main() {
a := make([]string, 100000)
for i := 1; i <= 100000; i++ {
a = append(a, strconv.Itoa(i))
}
fmt.Println(unsafe.Sizeof(a))
wg := sync.WaitGroup{}
wg.Add(3)
go plus(&wg, a)
go join(&wg, a)
go buffer(&wg, a)
wg.Wait()
}
func plus(wg *sync.WaitGroup, a []string) {
defer wg.Done()
start := time.Now()
var str string
for _, i := range a {
str = str + i
}
latency := time.Now().Sub(start)
fmt.Printf("plus latency: %s len: %d\n", latency, len(str))
}
func join(wg *sync.WaitGroup, a []string) {
defer wg.Done()
start := time.Now()
str := strings.Join(a, "")
latency := time.Now().Sub(start)
fmt.Printf("join latency: %s len: %d\n", latency, len(str))
}
func buffer(wg *sync.WaitGroup, a []string) {
defer wg.Done()
start := time.Now()
var str = bytes.NewBufferString("")
for _, i := range a {
str.WriteString(i)
}
latency := time.Now().Sub(start)
fmt.Printf("buffer latency: %s len: %d\n", latency, len(str.String()))
}
结果:
24
join latency: 2.536645ms len: 488895
buffer latency: 2.392455ms len: 488895
plus latency: 3.759257148s len: 488895
Process finished with exit code 0