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

前端 未结 1 1247
攒了一身酷
攒了一身酷 2020-12-20 11:03

I was writing a function for boolean 2d arrays:

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

Evaluating and testing it with

A          


        
相关标签:
1条回答
  • 2020-12-20 11:54

    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.

    0 讨论(0)
提交回复
热议问题