A quick mental model for understanding storage slot packing in the EVM
🧵
1/ Conceptually storage can be viewed as an astronomically large array
Within each index of the array we can store some data
Indexes start at 0 & go all the way to (2^256)-1
(2^256 is close to the number of atoms in the observable universe)
2/ Let's take this idea of an array and represent it with a set of boxes side by side stretching into the horizon
Each box has a number on it (array index) and holds some items (data) within it
3/ The items within these boxes are lego bricks
The smallest unit of lego is the 1x1 brick (which for us represents 1 byte of data)
Each box can hold up to 32 of these 1x1 bricks
4/ If we want to store bigger bricks we can
The block below is a 2x2 meaning it takes up 4 times as much space as a 1x1
This means we can only fit 8 of these in our box
We can use many different sizes of bricks within a single box to maximise how efficiently we use the space
5/ As we are adding our lego bricks we'll eventually get to a point where the next brick doesn't fit
Maybe the box is full or maybe it's a larger brick and there's only space for part of it
In either case we move on to the next box (array index) and begin filling that
6/ If we have filled the box entirely great we've made efficient use of the space
If we've left space in the previous box you may be thinking we can come back and fill it later
We can't once we move onto the next box we can only place our lego in that box or subsequent boxes
7/ What does not filling a box mean?
It means you might need more boxes (storage) for a set amount lego (data) than necessary
More boxes mean more $$$
If you'd had organised the lego bricks and treated it like a game of Tetris maybe you would have needed fewer boxes
8/ So how do I organise my lego you ask?
You do it via the ordering of your variable declarations in your code
In the image below we declare a uint8 then a uint32
This is the same as saying first I want to put the 1x1 brick in the box next I want the 2x2 brick
9/Let's now go back to the EVM and see what parallels we can draw
- EVM storage has the concept of a slot (lego box / array index)
- A slot can hold 32 bytes of data (32 1x1 bricks)
- Slots can be packed ie can hold multiple variables (lego bricks) if their sizes allow
10/
- We can organise which variables (bricks) will be stored where (boxes) by the order in which they are declared within our code
- This organisation means we may be able to fit more data into a smaller number of slots saving us $$$
11/ There is loads more to learn about storage in the EVM
How dynamic arrays are stored, how mappings are stored etc.
There's a lot I've simplified / glossed over for this example so use it as a way to remember a concept rather than as reference material
• • •
Missing some Tweet in this thread? You can try to
force a refresh