Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Optimizing object size by clustering

4.67/5 (16 votes)
5 Feb 2012CPOL 39.2K  
Optimizing object size by clustering
Consider the structure below:
C++
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.

C++
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:
C++
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;
};

C++
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.]

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)