The Storage Layout

Published by Mario Oettler on

In this topic, we take a more theoretical look at how the EVM stores variables.

Each variable gets its own index. The index is appointed in the order of the appearance in the contract.

The first variable gets the index 0, the second variable the index 1, etc.

But as always, it gets a bit more complicated when looking into the details.

Each index reserves a slot of 256 bits (= 32 bytes) for its value. In a hexadecimal representation, these are 64 digits.

If you want to store a value in this slot, let’s say 100 (=64 in hex), it takes up a whole slot, as you can see in the figure below.

Storing each variable in a new slot independently of its size is rather inefficient. For that reason, the compiler does something called packing. If you have a variable of the type uint32 and a variable of the type uint224, together, they take up a space of 256 bits. And since they fit into a single slot, Solidity packs them into the same slot.

On the left side, the uint32 variable is stored. The empty digits are filled with 0. Then the uint224 variable starts and takes up space until the slot is full.

Of course, it is possible to store more than two variables in one slot. This is used to save gas.

Categories:

if()