How slow are bit fields in C++

SmacL picture SmacL · Apr 14, 2010 · Viewed 8k times · Source

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;
  };
'
'
};

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.

Answer

Donal Fellows picture Donal Fellows · Apr 14, 2010

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...

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