Julia 中的 Array{Bool} 和 BitArray 有什么区别,它们之间有什么关系? [英] What's the difference between Array{Bool} and BitArray in Julia and how are they related?

查看:20
本文介绍了Julia 中的 Array{Bool} 和 BitArray 有什么区别,它们之间有什么关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为布尔二维数组编写一个函数:

I was writing a function for boolean 2d arrays:

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

评估和测试它

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

返回

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

显然,randbool() 生成一个 BitArray,而我假设 randbool() 会生成一个 Array{Bool}.

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

Array{Bool}BitArray 有什么关系?为什么它们都存在?

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

我能否编写 foo() 使其使用单一方法接受两种输入类型(因为我看不出有什么区别)?

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

推荐答案

一个 Array{Bool} 将每个 true/false 值存储为 Bool,在内部表示为 UInt8.因此,如果您的数组有 N 个元素,则需要 N 个字节来存储它.

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.

BitArray 将每个 true/false 值存储为单个位,其中(概念上)8 个被打包到单个 UInt8 中.因此,只需要 N/8 个字节来存储数组.BitArray 还定义了为您处理所有必需的位旋转操作的方法.

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.

根据操作的不同,BitArray 有时比对应的 Array{Bool} 慢,有时更快.但总的来说,性能差异很小,所以使用 BitArray 是有意义的,除非你有特定的理由不这样做.但总的来说,它们是可以互换的.

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.

请注意,两者都是 AbstractArray{Bool} 的子类型:

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.

这篇关于Julia 中的 Array{Bool} 和 BitArray 有什么区别,它们之间有什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆