- 6
NewBuffer(make([]byte,0,N))?leaf bebop– leaf bebop2018-01-19 06:25:26 +00:00CommentedJan 19, 2018 at 6:25
2 Answers2
Adding some additional info here. The quick way to create a new buffer is briefly mentioned at the end of the doc string:
b := new(bytes.Buffer)or
b := &bytes.Buffer{}TheBuffer struct define includes a 64 byte internalbootstrap field that is initially used for small allocations. Once the default size is exceeded, a byte sliceBuffer.buf is created and internally maintained.
As @leafbebop suggested we can pre-initalize thebuf field of theBuffer struct using a new slice.
b := bytes.NewBuffer(make([]byte,0,N))I also found another option to use theGrow() method:
b := new(bytes.Buffer)b.Grow(n)Also it's interesting to point out that the internalbuf slice will grow at a rate ofcap(buf)*2 + n. This means that if you've written 1MB into a buffer and then add 1 byte, yourcap() will increase to2097153 bytes.
Comments
Thebytes.buffer zero value is usable as is, so you can skip the initialization step. Code snippet fromdocs.
var b bytes.Buffer // A Buffer needs no initialization.b.Write([]byte("Hello "))Comments
Explore related questions
See similar questions with these tags.
