Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

disadvantages of using bitfields in memory

Tags:

c

linux

gcc

I am in a memory constrained x64 system and I need to hold a lot of data in memory. What are the disadvantages of using this kind of data structure.

struct entity
{
  unsigned int hash : 26;
  unsigned int timestamp : 14; 
} __attribute__ ((__packed__));

I know that using bit fields is discouraged, but what are the worst drawbacks in using this non aligned data structure.

The structure will be used in memory storage and some performance degradation is expected.

like image 388
Steve Perkson Avatar asked Dec 28 '22 00:12

Steve Perkson


1 Answers

Disadvantages (non-exhaustive list):

  • Not portable (in the sense that the C standard places few constraints on how bitfields should be packed)
  • Potential performance impact compared to "native" types (compiler has to do bit-slicing/mis-aligned accesses)
  • Can't take address of individual members
  • Can't apply sizeof to individual members
  • Confusing semantics when it comes to integer promotions, etc. (see e.g. Type of unsigned bit-fields: int or unsigned int or Comparison of a bitfield vs a (negative) integer, undefined behavior or compiler bugs?)
like image 188
Oliver Charlesworth Avatar answered Jan 05 '23 22:01

Oliver Charlesworth