Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Julia optimize boolean arrays for memory?

In Julia and all other languages I can think of, a boolean takes up 8 bits of memory because otherwise, it wouldn't be addressable in memory. For example:

x = true
println(sizeof(x)) # => 1

However, when I create an array of booleans, each element still takes up an entire byte:

x = [true, false, true, false, true, true, false, false]
println(sizeof(x)) # => 8

In other languages, such as C++, an array of eight booleans will only take up 1 byte, since each boolean really only needs 1 bit. Is it possible to get Julia to optimize boolean arrays like this too so I can save memory? If so, how?

like image 807
Michael M. Avatar asked Apr 14 '26 18:04

Michael M.


1 Answers

Yes, Julia can optimize Boolean vector for memory. Use the BitVector type (and the BitArray type). For example:

julia> bv = BitVector(rand(Bool, 1_000));

julia> size(bv)
(1000,)

julia> sizeof(bv)
128

All the standard Boolean operations are supported.

The documentation link is: https://docs.julialang.org/en/v1/base/arrays/#Base.BitArray

And the ? help mode in the REPL also gives a short description on BitVector.

Added: DNF correctly pointed out that:

julia> using Random

julia> bv = bitrand(1_000);

would be the efficient way to create a random bit vector.

like image 81
Dan Getz Avatar answered Apr 16 '26 11:04

Dan Getz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!