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?
CodePudding user response:
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.