32

I was writing a function for boolean 2d arrays:

function foo(A::Array{Bool,2})
   ...
end

Evaluating and testing it with

A = randbool(3,3)
foo(A)

returns

ERROR: 'foo' has no method matching foo(::BitArray{2})

Obviously, randbool() generates a BitArray, whereas I assumed randbool() would yield an Array{Bool}.

How are Array{Bool} and BitArray related? Why do they both exist?

Can I write foo() in such a way that it accept both input types using a single method (since I can't see a difference)?

1
  • 3
    Your assumption about the behavior of randbool isn't unreasonable — it's a pretty bad name! It's been deprecated in 0.4 and renamed to bitrand (which sounds more like it'd create a BitArray). And there is a new method rand(Bool, …) to explicitly create an array of Bool. You can start using these new definitions in 0.3 with the Compat package.
    – mbauman
    Apr 14, 2015 at 13:51

1 Answer 1

35

An Array{Bool} stores each true/false value as a Bool, which is represented internally as a UInt8. So if your array has N elements, it will take N bytes to store it.

A BitArray stores each true/false value as a single bit, with (conceptually) 8 of them packed into a single UInt8. Consequently, it takes only N/8 bytes to store the array. A BitArray also has methods defined that handle all the required bit-twiddling operations for you.

Depending on the operation, BitArrays are sometimes slower than the corresponding Array{Bool}, and sometimes faster. But by and large the performance differences are quite small, so it makes sense to use BitArrays unless you have a specific reason not to. But overall they are fairly interchangeable.

Note that both are subtypes of AbstractArray{Bool}:

julia> BitArray <: AbstractArray{Bool}
true

julia> Array{Bool} <: AbstractArray{Bool}
true

This makes it easy to write generic methods that take either one.

1
  • 5
    AbstractArray{Bool} is exactly the type I was looking for.
    – reschu
    Apr 15, 2015 at 10:14

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.