繁星淼淼
这取决于用例。在这两种情况下都比(样本:1、2、3、4)bytes.Buffer更快。append使用buf.Write(make([]byte, 16))需要4.6482659s,使用buf = append(buf, make([]byte, 16)...)需要6.6623811s。对于样本 5、6:使用buf = append(buf, byte(i))take 445.0255ms,Using buf.WriteByte(byte(i))take1.4410824s并bytes.Buffer使用内置函数copy,速度很快:// 写入将 p 的内容附加到缓冲区,根据需要增长缓冲区。返回值n是p的长度;错误总是零。如果// 缓冲区变得太大,Write 会出现 ErrTooLarge 恐慌。func (b *Buffer) Write(p []byte) (n int, err error) { b.lastRead = opInvalid m := b.grow(len(p)) return copy(b.buf[m:], p), nil}bytes.Buffer耗时 4.8892797s,append耗时 7.7514434s查看这些基准:1-使用append:package mainimport ( "fmt" "time")func main() { buf := []byte{} data := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} t := time.Now() for i := 0; i < 100000000; i++ { buf = append(buf, data...) } fmt.Println(time.Since(t)) fmt.Println(len(buf))}输出:7.7514434s16000000002-使用bytes.Bufferpackage mainimport ( "bytes" "fmt" "time")func main() { buf := &bytes.Buffer{} data := []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16} t := time.Now() for i := 0; i < 100000000; i++ { buf.Write(data) } fmt.Println(time.Since(t)) fmt.Println(buf.Len())}输出:4.8892797s16000000003-bytes.Buffer使用make([]byte, 16):package mainimport ( "bytes" "fmt" "time")func main() { buf := &bytes.Buffer{} t := time.Now() for i := 0; i < 100000000; i++ { buf.Write(make([]byte, 16)) } fmt.Println(time.Since(t)) // 4.6482659s fmt.Println(buf.Len()) //1600000000}4-append使用make([]byte, 16):package mainimport ( "fmt" "time")func main() { buf := []byte{} t := time.Now() for i := 0; i < 100000000; i++ { buf = append(buf, make([]byte, 16)...) } fmt.Println(time.Since(t)) // 6.6623811s fmt.Println(len(buf)) // 1600000000}5- 使用buf = append(buf, byte(i))需要445.0255ms:package mainimport ( "fmt" "time")func main() { buf := []byte{} t := time.Now() for i := 0; i < 100000000; i++ { buf = append(buf, byte(i)) } fmt.Println(time.Since(t)) // 445.0255ms fmt.Println(len(buf)) // 100000000}6- 使用buf.WriteByte(byte(i))需要1.4410824s:package mainimport ( "bytes" "fmt" "time")func main() { buf := &bytes.Buffer{} t := time.Now() for i := 0; i < 100000000; i++ { buf.WriteByte(byte(i)) } fmt.Println(time.Since(t)) // 1.4410824s fmt.Println(buf.Len()) // 100000000}