Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to design objects for performance

Tags:

Whilst reading a book about physics engine development recently, I came across a design decision which I have never even considered before. This relates to the way the raw bytes in memory are addressed by the CPU.

Consider the following class:

class Foo
{
    public:
        float x;
        float y;
        float z;

        /* Constructors and Methods */

    private:
        float padding;
}

The author claims that the padding, increasing the size of the object to a quad-word in x86 architecture, results in a noticeable benefit to performance. This is because 4 words sit more cleanly in memory than 3, what does this mean? Padding out an object with redundant data to increase performance seems pretty paradoxical to me.

This also begs another question, what about objects that are 1 or 2 words in size? If my class is something like:

class Bar
{
    public:
        float x;
        float y;

        /* Constructors and Methods */

    private:
        /* padding ?? */
}

Should I add padding to this class so that it sits more cleanly in memory?