Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Array{Bool} and BitArray in Julia and how are they related?

Tags:

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)?

like image 979
reschu Avatar asked Apr 14 '15 08:04

reschu


People also ask

What is array in Julia?

In Julia, arrays are actually mutable type collections which are used for lists, vectors, tables, and matrices. That is why the values of arrays in Julia can be modified with the use of certain pre-defined keywords. With the help of push! command you can add new element in array. Similarly, with the help of splice!

How do you declare an array in Julia?

An Array in Julia can be created with the use of a pre-defined keyword Array() or by simply writing array elements within square brackets([]). There are different ways of creating different types of arrays.

How do you write a vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do you create a matrix in Julia?

Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).


1 Answers

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.

like image 159
tholy Avatar answered Nov 09 '22 20:11

tholy