C ++中的位域有多慢 [英] How slow are bit fields in C++

查看:43
本文介绍了C ++中的位域有多慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C ++应用程序,其中包括许多带有手动控制的位字段的结构,例如

I have a C++ application that includes a number of structures with manually controlled bit fields, something like

#define FLAG1   0x0001  
#define FLAG2   0x0002      
#define FLAG3   0x0004      

class MyClass
{
'
'
  unsigned Flags;

  int IsFlag1Set() { return Flags & FLAG1; }
  void SetFlag1Set() { Flags |= FLAG1; }
  void ResetFlag1() { Flags &= 0xffffffff ^ FLAG1; }
'
'
};

出于明显的原因,我想将其更改为使用位字段,例如

For obvious reasons I'd like to change this to use bit fields, something like

class MyClass
{
'
'
  struct Flags
  {
    unsigned Flag1:1;
    unsigned Flag2:1;
    unsigned Flag3:1;
  };
'
'
};

进行此切换时,我要担心的一点是,我在此站点上遇到了许多引用,指出C ++中的慢速位字段如何.我的假设是它们仍比上面显示的手动代码快,但是是否有任何硬性参考资料涵盖在各种平台(尤其是32位和64位窗口)上使用位字段的速度含义.该应用程序处理内存中的大量数据,并且必须既快速又具有内存效率,这很可能就是为什么首先以这种方式编写它的原因.

The one concern I have with making this switch is that I've come across a number of references on this site stating how slow bit fields are in C++. My assumption is that they are still faster than the manual code shown above, but is there any hard reference material covering the speed implications of using bit fields on various platforms, specifically 32bit and 64bit windows. The application deals with huge amounts of data in memory and must be both fast and memory efficient, which could well be why it was written this way in the first place.

推荐答案

这两个示例在速度上应该非常相似,因为在这两种情况下,编译器最终都必须发出几乎相同的位屏蔽指令.要知道哪种方法最好,请运行一些简单的实验.但是,如果结果不确定,请不要感到惊讶.这就是我的预测...

The two examples should be very similar in speed because the compiler will have to end up issuing pretty much the same instructions for bit-masking in both cases. To know which is really best, run a few simple experiments. But don't be surprised if the results are inconclusive; that's what I'm predicting...

您可能会更好地说这些位字段的类型是 bool .

You might be better saying that the bitfields are of type bool though.

这篇关于C ++中的位域有多慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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