Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate uninitialized slice

Is there some way to allocate an uninitialized slice in Go? A frequent pattern is to create a slice of a given size as a buffer, and then only use part of it to receive data. For example:

b := make([]byte, 0x20000) // b is zero initialized
n, err := conn.Read(b)
// do stuff with b[:n]. all of b is zeroed for no reason

This initialization can add up when lots of buffers are being allocated, as the spec states it will default initialize the array on allocation.

like image 548
Matt Joiner Avatar asked Aug 27 '26 10:08

Matt Joiner


1 Answers

You can get non zeroed byte buffers from bufs.Cache.Get (or see CCache for the concurrent safe version). From the docs:

NOTE: The buffer returned by Get is not guaranteed to be zeroed. That's okay for e.g. passing a buffer to io.Reader. If you need a zeroed buffer use Cget.

like image 89
zzzz Avatar answered Aug 30 '26 11:08

zzzz