Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...