0

Consider the following excerpt from Prometheus source code:

func (ls Labels) String() string {
    var bytea [1024]byte // On stack to avoid memory allocation while building the output.
    b := bytes.NewBuffer(bytea[:0])

...
}

How exactly does defining byte array bytea [1024]byte and using its zero-length slicing result bytea[:0] to create new *bytes.Buffer help to avoid memory allocation?

5
  • It's giving the buffer a pre-allocated slice to use, rather than letting the buffer grow to that size on its own. This is explained exactly in the bytes.NewBuffer docs as well, what isn't clear in this use case? Commented Jun 20 at 16:19
  • To do that, buf should have the desired capacity but a length of zero. It says nothing about memory allocation. And I can do it with just make([]byte, 0, 1024), I don't need an array Commented Jun 20 at 16:23
  • closely related: stackoverflow.com/a/48337682 Commented Jun 23 at 2:34
  • @Mr_Pink I can't find a suitable dupe target. Feel free to post an answer, if you want. Thanks Commented Jun 23 at 2:35
  • I actually checked and the escape analysis can detect whether the slice escapes or not along with the buffer just fine. This is really just a syntax choice, using the array doesn't change the memory allocation at all. I don't know if we need an official answer to an inaccurate comment in a random package's code. Commented Jun 23 at 14:31

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.