枚举 BitArray 是否会导致大量装箱/拆箱?
System.BitArray 仅实现非泛型 IEnumerable,它返回 IEnumerator.Current 属性的对象。 是否在 BitArray 上运行 foreach - 例如
foreach (bool b in bitArray)
{
// ...
}
装箱和拆箱每个位值?
查看反射器中的位数组枚举器,看起来它在每次调用 MoveNext() 时都会执行一个新的位掩码,而不是更聪明的方法。 是否有更有效的方法来枚举 BitArray,或者具有相同存储特性的 BitArray 替代品? (List
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,会引起很多拳击。 然而,在大多数情况下,我实际上并不认为这会对性能造成太大影响。 这很烦人,但我怀疑许多现实世界的应用程序花费大量时间装箱/拆箱(或事后清理盒子,这当然是其他成本)。 在你努力避免这种情况之前,可能值得检查一下。
不过,您可以相当轻松地在其上编写自己的迭代器...特别是如果您不关心“版本”更改时的中断。 例如:
如果您在迭代时更改数组,那么几乎肯定会发生不好的事情 - 特别是如果您更改长度!
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:
Bad things will almost certainly happen if you do change the array while you're iterating though - particularly if you change the length!