Golang 字符串拼装方式性能对比

吃一堑消化不良 ·
实际上这个测试是有问题的, 41 time of way(3)=2.277063ms 为什么3的长度是41,和其他的不一样? 下面是正确的代码 ``` b := bytes.Buffer{} b.WriteString(s) b.WriteString("[") b.WriteString(v) b.WriteString("]") s = b.String() ``` ``` 410000 time of way(0)=689.519619ms 410000 time of way(1)=446.032309ms 410000 time of way(2)=1.020859617s 410000 time of way(3)=2.148212771s 410000 time of way(4)=698.66µs way 0 is 986.9 times of way 4 way 1 is 638.4 times of way 4 way 2 is 1461.2 times of way 4 way 3 is 3074.8 times of way 4 ``` 顺便说一下为什么,因为string是只读的,导致每次处理都会先复制成[]byte,完成拼接再转回来,时间全花在复制上面了,也只有4避免了大量复制。 ``` b := bytes.Buffer{} b.Write(t) //var t = []byte{} b.WriteString("[") b.WriteString(v) b.WriteString("]") t = b.Bytes() ``` 这是3的另一个版本,减掉了一个转换,耗时直接减少了1/4 time of way(3)=1.598158881s
#1
更多评论
基于上一位大佬的评论的完整代码 ```go package main import ( "bytes" "fmt" "strings" "time" ) func benchmarkStringFunction(n int, index int) (d time.Duration) { v := "ni shuo wo shi bu shi tai wu liao le a?" var s string var buf bytes.Buffer var t = []byte{} t0 := time.Now() for i := 0; i < n; i++ { switch index { case 0: // fmt.Sprintf s = fmt.Sprintf("%s[%s]", s, v) case 5: s = fmt.Sprintf("%s[%v]", s, v) case 6: s = fmt.Sprintf("%v[%v]", s, v) case 1: // string + s = s + "[" + v + "]" case 2: // strings.Join s = strings.Join([]string{s, "[", v, "]"}, "") case 3: // temporary bytes.Buffer b := bytes.Buffer{} b.Write(t) b.WriteString("[") b.WriteString(v) b.WriteString("]") //s = b.String() t = b.Bytes() case 4: // stable bytes.Buffer buf.WriteString("[") buf.WriteString(v) buf.WriteString("]") } if i == n-1 { if index == 4 { // for stable bytes.Buffer s = buf.String() } if index == 3 { s = string(t) } fmt.Println("way=", index, ", len(s)=", len(s)) // consume s to avoid compiler optimization } } t1 := time.Now() d = t1.Sub(t0) fmt.Printf("time of way(%d)=%v\n", index, d) return d } func main() { k := 7 d := [7]time.Duration{} for i := 0; i < k; i++ { d[i] = benchmarkStringFunction(20000, i) } for i := 0; i < k; i++ { fmt.Printf("way %d=%v is %6.1f times of way %d\n", i, d[i], float32(d[i])/float32(d[k-1]), k-1) } } ```
#2
```bash way= 0 , len(s)= 820000 time of way(0)=1.836864086s way= 1 , len(s)= 820000 time of way(1)=766.44119ms way= 2 , len(s)= 820000 time of way(2)=1.017533572s way= 3 , len(s)= 820000 time of way(3)=3.305793765s way= 4 , len(s)= 820000 time of way(4)=777.359µs way= 5 , len(s)= 820000 time of way(5)=1.89599892s way= 6 , len(s)= 820000 time of way(6)=1.888661772s way 0=1.836864086s is 1.0 times of way 6 way 1=766.44119ms is 0.4 times of way 6 way 2=1.017533572s is 0.5 times of way 6 way 3=3.305793765s is 1.8 times of way 6 way 4=777.359µs is 0.0 times of way 6 way 5=1.89599892s is 1.0 times of way 6 way 6=1.888661772s is 1.0 times of way 6 ```
#3