這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//上資料結構,bytes Buffertype Buffer struct {buf []byte // byte切片off int // 從&buf[off]地址讀資料, 從&buf[len(buf)]地址寫資料runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Runebootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation.lastRead readOp // last read operation, so that Unread* can work correctly.}
再來看看我們bytes Buffer裡面write是怎麼實現的
func (b *Buffer) WriteString(s string) (n int, err error) {b.lastRead = opInvalid /// Non-read operation 不需要讀的標誌 等於0m := b.grow(len(s)) // 增長大小(準確來說是調整資料在buf中位置,也不一定增長),m當然是老資料末尾return copy(b.buf[m:], s), nil //copy一下資料,從m開始}
最最重要的看過來
func (b *Buffer) grow(n int) int {m := b.Len() //func (b *Buffer) Len() int { return len(b.buf) - b.off }// m就是buf的len 減去(-) b.off(讀開始位置)if m == 0 && b.off != 0 {b.Truncate(0) //下面給予顯示} //調整大小和位置if len(b.buf)+n > cap(b.buf) {var buf []byteif b.buf == nil && n <= len(b.bootstrap) {buf = b.bootstrap[0:] //這個bootstrap緩衝了buf的切片,說是防止重allocation} else if m+n <= cap(b.buf)/2 { // 二倍申請新的slice的原則copy(b.buf[:], b.buf[b.off:])buf = b.buf[:m]} else {// not enough space anywherebuf = makeSlice(2*cap(b.buf) + n)copy(buf, b.buf[b.off:])}b.buf = bufb.off = 0}b.buf = b.buf[0 : b.off+m+n] //賦值咯return b.off + m}
再看看它用到過的函數 Truncate函數,縮減切片
func (b *Buffer) Truncate(n int) {b.lastRead = opInvalidswitch {case n < 0 || n > b.Len():panic("bytes.Buffer: truncation out of range")case n == 0:// Reuse buffer space.b.off = 0}b.buf = b.buf[0 : b.off+n]}
makeSlice函數
func makeSlice(n int) []byte {// If the make fails, give a known error.defer func() {if recover() != nil {panic(ErrTooLarge)}}()return make([]byte, n) //其實還是調用這個make}
最後看看一個使用樣本咯
package mainimport ("bytes""fmt""strconv""time")func main() {var buffer bytes.Bufferttime := time.Now().UnixNano()for i := 0; i < 10000000; i++ {buffer.WriteString(strconv.Itoa(i))}ttime1 := time.Now().UnixNano()//取內容buffer.Bytes() 或者 buffer.String()fmt.Printf("time cal %f %d\n", float64(ttime1-ttime)/float64(1*time.Second), len(buffer.String()))}
總結:bytes buffer:就是寫byte或者字串string的一個容器