On Jun 27, 1:40 pm, Philipp <sicsic...@freesurf.chwrote:
I have a class Position which declares a bit field
class Position{
public:
Position(int i=0, int j=0, int k=0);
// Positions have to be within the range: [0..8191,0..8191,0..7]
void setPosition(int i, int j, int k);
int getI();
int getJ();
int getK();
friend ostream& operator<< (ostream& outs, const Position &rhs);
private:
unsigned short i:13;
unsigned short j:13;
unsigned short k:3;
};
How efficient is this technique to save memory (I have a lot of Position
objects)? What size of memory will the three vars i,j,k really occupy in
the memory?
It depends somewhat on the implementation, but at the very
least, the last two should pack into a single 16 element; if the
size of an int is more than 29 bits, they should all pack into a
single int. On a machine with 8 bit bytes and byte addressing,
I would expect 4 bytes for the lot; without the bit fields, 6,
or possibly even 8 bytes. So you gain some memory; where bit
fields really start gaining memory, of course, is when you have
a lot of one or two bit fields.
You don't get anything for free, however. Accessing bit-fields
is considerably slower than accessing ints. In some cases, this
can be offset by improved locality; you get more elements in
each page and/or cache line. Most of the time, however,
bit-fields have a very negative impact on run-time. (Note that
writing to a bit-field will normally require two accesses, a
read and a write.)
Does this depend on the compiler (icc 7.1 on linux)? On the architecture
(i686)?
Somewhat. In practice, there's a pretty widespread concensus as
to what is "best practice" for "conventional" architectures, and
the comments above will almost certainly be valid for most, if
not all, mainstream compilers and machines today, and even for
most exotics. The exact layout of the bit-fields will vary,
however.
--
James Kanze (GABI Software) email:ja*********@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34