D
Derek
I have an application that creates lots of small objects that
represent a 2D axis-parallel plane. In short, I these little
objects look like this:
struct Plane {
float location;
enum { X, Y, Z } direction;
};
On my 32-bit platform this structure is 8 bytes, 4 of which
are used to store the direction, a 2-bit value. Memory is
very critical in my world and I'd like to reduce this struct
in size.
An interesting characteristic of my problem domain is that the
float in the Plane structure doesn't have to be exact. I can
sacrifice two LSB bits in the float's fractional part to store
the direction (X, Y, Z) -- and in the process reduce the struct
to 4 bytes, a big saving for my application.
Clearly this code will not be portable, so I'm looking for some
suggestions for alternative solutions or ways to make it less
kludgy:
class Plane {
public:
typedef enum { X, Y, Z } Direction;
Plane(float location, Direction direction) {
// Order matters -- set direction second
m_impl.location = location;
m_impl.direction.value = direction;
}
float getLocation() const {
return m_impl.location;
}
Direction getDirection() const {
return static_cast<Direction>(m_impl.direction.value);
}
private:
union Impl {
float location;
// Depends on the platform's IEEE float layout
struct Bits {
unsigned value : 2;
} direction;
} m_impl;
};
represent a 2D axis-parallel plane. In short, I these little
objects look like this:
struct Plane {
float location;
enum { X, Y, Z } direction;
};
On my 32-bit platform this structure is 8 bytes, 4 of which
are used to store the direction, a 2-bit value. Memory is
very critical in my world and I'd like to reduce this struct
in size.
An interesting characteristic of my problem domain is that the
float in the Plane structure doesn't have to be exact. I can
sacrifice two LSB bits in the float's fractional part to store
the direction (X, Y, Z) -- and in the process reduce the struct
to 4 bytes, a big saving for my application.
Clearly this code will not be portable, so I'm looking for some
suggestions for alternative solutions or ways to make it less
kludgy:
class Plane {
public:
typedef enum { X, Y, Z } Direction;
Plane(float location, Direction direction) {
// Order matters -- set direction second
m_impl.location = location;
m_impl.direction.value = direction;
}
float getLocation() const {
return m_impl.location;
}
Direction getDirection() const {
return static_cast<Direction>(m_impl.direction.value);
}
private:
union Impl {
float location;
// Depends on the platform's IEEE float layout
struct Bits {
unsigned value : 2;
} direction;
} m_impl;
};