bytes.NewBuffer(make([]byte, 0, <some size >)) allocates 4096 bytes buffer

305 views
Skip to first unread message

Gautam Saha

unread,
Jun 11, 2020, 12:50:41 PM6/11/20
to golang-nuts
Trying to allocate an in-memory  buff of small size (few bytes) using 
bytes.NewBuffer(make([]byte, 0, <some size >))
The allocated buffer has size 4096 bytes i.e. > than what I requested for. Why is this so?

Brian Candler

unread,
Jun 11, 2020, 1:23:29 PM6/11/20
to golang-nuts
Can you show how you came to that conclusion?  It seems to work as expected for me:
4096 bytes is typically a page, so maybe something is going on to do with allocation on page boundaries, but need to see your code.

Jan Mercl

unread,
Jun 11, 2020, 1:25:39 PM6/11/20
to Gautam Saha, golang-nuts
Nowhere the docs say one can control the buffer size. Instead, the
passed []byte is documented to be used "as its initial contents", not
"as its initial buffer".

Brian Candler

unread,
Jun 12, 2020, 6:13:14 AM6/12/20
to golang-nuts
However, it does say "The new Buffer takes ownership of buf" - why would it do that if it were allocating a new buffer and taking a copy of the original?

The code has the answer, it's just a single line:

func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} }

ISTM that the Buffer object is simply using the buf you provided.  I don't understand where the claim comes from that (a) it allocates a buffer, and (b) the allocated buffer is of size 4096 bytes.

Gautam Saha

unread,
Jun 12, 2020, 9:45:47 AM6/12/20
to golang-nuts
Probably I was doing something wrong. @Brian your snippet works as I would have expected.
Reply all
Reply to author
Forward
0 new messages