Golang byte 拼接方法性能对比
最近项目上遇到需要将[]Byte进行拼接的需求,对[]Byte拼接的各种方法进行了对比,测试代码如下:
package main
import (
"bytes"
"fmt"
"time"
)
func main() {
count := 1000000
oneSerail := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
s0 := time.Now()
for i := 0; i < count; i++ {
str0 := make([][]byte, 8)
str0[0] = oneSerail[0:4]
str0[1] = oneSerail[4:6]
str0[2] = oneSerail[6:10]
str0[3] = oneSerail[0:2]
str0[4] = oneSerail[2:6]
str0[5] = oneSerail[6:8]
str0[6] = oneSerail[0:4]
str0[7] = oneSerail[8:10]
bytes.Join(str0, []byte(""))
}
e0 := time.Now()
d0 := e0.Sub(s0)
fmt.Printf("time of way(0)=%v\n", d0)
s1 := time.Now()
for i := 0; i < count; i++ {
str1 := make([]byte, 0)
str1 = append(str1, oneSerail[0])
str1 = append(str1, oneSerail[1])
str1 = append(str1, oneSerail[2])
str1 = append(str1, oneSerail[3])
str1 = append(str1, oneSerail[4])
str1 = append(str1, oneSerail[5])
str1 = append(str1, oneSerail[6])
str1 = append(str1, oneSerail[7])
str1 = append(str1, oneSerail[8])
str1 = append(str1, oneSerail[9])
str1 = append(str1, oneSerail[0])
str1 = append(str1, oneSerail[1])
str1 = append(str1, oneSerail[2])
str1 = append(str1, oneSerail[3])
str1 = append(str1, oneSerail[4])
str1 = append(str1, oneSerail[5])
str1 = append(str1, oneSerail[6])
str1 = append(str1, oneSerail[7])
str1 = append(str1, oneSerail[8])
str1 = append(str1, oneSerail[9])
str1 = append(str1, oneSerail[0])
str1 = append(str1, oneSerail[1])
str1 = append(str1, oneSerail[2])
str1 = append(str1, oneSerail[3])
str1 = append(str1, oneSerail[4])
str1 = append(str1, oneSerail[5])
str1 = append(str1, oneSerail[6])
str1 = append(str1, oneSerail[7])
str1 = append(str1, oneSerail[8])
str1 = append(str1, oneSerail[9])
}
e1 := time.Now()
d1 := e1.Sub(s1)
fmt.Printf("time of way(1)=%v\n", d1)
s2 := time.Now()
for i := 0; i < count; i++ {
str2 := make([]byte, 0)
str2 = append(str2, oneSerail[0:4]...)
str2 = append(str2, oneSerail[4:6]...)
str2 = append(str2, oneSerail[6:10]...)
str2 = append(str2, oneSerail[0:2]...)
str2 = append(str2, oneSerail[2:6]...)
str2 = append(str2, oneSerail[6:8]...)
str2 = append(str2, oneSerail[0:4]...)
str2 = append(str2, oneSerail[4:8]...)
str2 = append(str2, oneSerail[8:10]...)
}
e2 := time.Now()
d2 := e2.Sub(s2)
fmt.Printf("time of way(2)=%v\n", d2)
s3 := time.Now()
for i := 0; i < count; i++ {
str3 := make([]byte, 30)
for j := 0; j < 30; j++ {
str3[j] = oneSerail[j%10]
}
}
e3 := time.Now()
d3 := e3.Sub(s3)
fmt.Printf("time of way(3)=%v\n", d3)
}
运行结果如下:
time of way(0)=152.2175ms
time of way(1)=141.7367ms
time of way(2)=125.7664ms
time of way(3)=69.8702ms
结果分析:
1,bytes.Join耗时最久,可能是因为在进行Join的时候需要进行重新内存分配导致;
2,单byte进行append耗时比bytes.Join短,但是有限;
3,[]byte…进行append的耗时比1和2短,因为append操作的次数比2少很多;
4,最快的方法,但是需要预知拼接后byte组的大小;
总结:golang的内存分配真的很耗时。