枚举 BitArray 是否会导致大量装箱/拆箱?

发布于 2024-07-27 18:01:52 字数 369 浏览 4 评论 0原文

System.BitArray 仅实现非泛型 IEnumerable,它返回 IEnumerator.Current 属性的对象。 是否在 BitArray 上运行 foreach - 例如

foreach (bool b in bitArray)
{
    // ...
}

装箱和拆箱每个位值?

查看反射器中的位数组枚举器,看起来它在每次调用 MoveNext() 时都会执行一个新的位掩码,而不是更聪明的方法。 是否有更有效的方法来枚举 BitArray,或者具有相同存储特性的 BitArray 替代品? (List等每个 bool 使用一个字节,而不是单个位,因此使用 8 倍的空间)

System.BitArray only implements the non-generic IEnumerable, which returns an Object for the IEnumerator.Current property. Does running a foreach over a BitArray - eg

foreach (bool b in bitArray)
{
    // ...
}

box and unbox each and every bit value?

Looking at the bitarray enumerator in reflector, it looks like it does a fresh bitmask on every call of MoveNext() rather than something cleverer. Is there a more efficient way of enumerating a BitArray, or a replacement for BitArray that has the same storage characteristics? (List<bool> etc uses one byte per bool, rather than a single bit, so uses 8x as much space)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぺ禁宫浮华殁 2024-08-03 18:01:52

是的,会引起很多拳击。 然而,在大多数情况下,我实际上并不认为这会对性能造成太大影响。 这很烦人,但我怀疑许多现实世界的应用程序花费大量时间装箱/拆箱(或事后清理盒子,这当然是其他成本)。 在你努力避免这种情况之前,可能值得检查一下。

不过,您可以相当轻松地在其上编写自己的迭代器...特别是如果您不关心“版本”更改时的中断。 例如:

public static IEnumerable<bool> EnumerateBitArray(BitArray bitArray)
{
    for (int i=0; i < bitArray.Length; i++)
    {
        yield return bitArray[i];
    }
}

如果您在迭代时更改数组,那么几乎肯定会发生不好的事情 - 特别是如果您更改长度!

Yes, it will cause a lot of boxing. However, in most cases I wouldn't actually expect that to hurt performance too much. It's annoying, but I doubt that many real world apps spend a significant amount of time boxing/unboxing (or cleaning up the boxes afterwards, which is the other cost of course). It's probably worth checking that before you go to any great effort to avoid it.

You could write your own iterator over it fairly easily though... particularly if you didn't care about breaking if the "version" changes. For example:

public static IEnumerable<bool> EnumerateBitArray(BitArray bitArray)
{
    for (int i=0; i < bitArray.Length; i++)
    {
        yield return bitArray[i];
    }
}

Bad things will almost certainly happen if you do change the array while you're iterating though - particularly if you change the length!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文