65.9K
CodeProject is changing. Read more.
Home

Optimizing object size by clustering

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (15 votes)

Jan 27, 2012

CPOL
viewsIcon

39325

Optimizing object size by clustering

Consider the structure below:
struct DrawingBoard
{
    bool m_bIsEditable;
    float m_fXPos;
    float m_fYPos;
    int m_iOpacity;
    bool m_bResizable;
    short m_sSchema;
    bool m_bCanExport;
    float m_fBorderThickness;
    bool m_bApplyCustomColor;
    int m_iTransparency;
};
Its members are randomly organized (or rather organized basing on their functionality) without taking into account the way they packed into memory. If we query the size of an object of this structure on a 32-bit OS (with packing of 8), then we will get 36 bytes.
DrawingBoard structDrawingBoard;
size_t n = sizeof( structDrawingBoard );
// n is 36
But if we group them based on their type and arrange them in increasing order of their size, then we COULD reduce the size:
struct DrawingBoard
{
    bool m_bIsEditable;
    bool m_bResizable;
    bool m_bApplyCustomColor;
    bool m_bCanExport;
    short m_sSchema;
    int m_iOpacity;
    int m_iTransparency;
    float m_fXPos;
    float m_fYPos;
    float m_fBorderThickness;
};
DrawingBoard structDrawingBoard;
size_t n = sizeof( structDrawingBoard );
// n is 28
Now the size of structDrawingBoard is only 28 bytes. [We can still optimize by using bit fields or playing with pragma packing, BUT performace will be AFFECTED.]