kevin gomes
kevin gomes

Reputation: 1815

how is padding beneficial?

struct MixedData
{
    char Data1;
    short Data2;
    short Data3;
    double Data4;
    int Data5;
    double Data6;
};

The above struct will be automatically 'padded'. But I do not understand how 'padding' is beneficial.

Upvotes: 2

Views: 116

Answers (4)

tangrs
tangrs

Reputation: 9930

Just to expand on the answers already given with a visual representation.

When a word is aligned in memory, it looks like this, and only requires one reading.

+-------------------------+-------------------------+
| XX XX XX XX XX XX XX XX | 12 34 56 78 90 ab cd ef |
+-------------------------+-------------------------+
                           ^-----------------------^
                                     Cycle 1

When it's unaligned, some architectures require two cycles to fetch the word since it can't read past a boundary at a time or that memory addresses are internally represented as multiples of the word size. They need to fetch twice the amount of data, discard the useless parts and combine the useful parts to form the word.

+-------------------------+-------------------------+
| XX XX XX XX XX 12 34 56 | 78 90 ab cd ef XX XX XX |
+-------------------------+-------------------------+
                ^--------^ ^--------------^
                  Cycle 1      Cycle 2

Upvotes: 3

dtech
dtech

Reputation: 49289

Because most platforms suffer a performance penalty when reading unaligned data. For example, a 64 bit wide memory controller can read a double in one "cycle" as long as it is aligned properly, if not, it will take 2 cycles to read it and load the MC unnecessarily. Some platforms cannot even read unaligned data. That is why padding is a must to ensure everything is aligned optimally.

Upvotes: 4

Joseph Quinsey
Joseph Quinsey

Reputation: 9962

Some computers (e.g. RISC, and at one time ARM-based) can only access, say, a double only at specific memory boundaries. Other computers, such as 8086-based family, can do arbitrary accesses, but have a performance penalty.

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409196

On some CPU architectures, trying to load a word from an unaligned memory address can take many CPU cycles, while loading a word from an aligned address will take few CPU cycles. Some CPU architectures even can't load from unaligned addresses.

The compiler is helpful enough to try and place structure member variables on optimal positions for the CPU.

Upvotes: 4

Related Questions