golang bytes buffer代碼剖析

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
//上資料結構,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的一個容器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.