Cost of a bool slice in Go

Val Deleplace
2 min readAug 17, 2020

--

How much memory do 10 million bools take up?

Short answer

10MB. This is 8x as large as the number of bits that I actually care about.

Details

In Go all elements of a slice are addressable. The smallest addressable unit being the byte, a slice of bools looks in memory like a contiguous sequence of bytes, containing only 1 useful bit per byte.

Memory representation of a large slice

The slice header itself (1 pointer + 2 integers) is negligible: its memory occupancy is dwarfed by the size of the backing array.

I suspected that on my 64-bit computer, the minimal addressable unit would be a 64-bit word, incurring a 64x overhead for each useful bit! Fortunately, bytes are still individually addressable, keeping the overhead to 8x.

If you’re worried about such a waste of memory, have a look at 7 ways to implement a Bit set in Go to learn about more compact options to store a large number of bits.

Zeroes and ones

--

--

Val Deleplace

Engineer on cloudy things @Google. Opinions my own. Twitter @val_deleplace