Gas optimization Series Part - 1

Saksham ThapaSaksham Thapa
2 min read

Starting this gas optimization series where i'll be writing whatever i learn about gas optimization in solidity.

Deciphering Solidity: Does adding a PAYABLE keyword actually save GAS? | by  Zaryab Afser | Coinmonks | Medium

"How far will you go to save gas ?" is a pretty viable question, will you use the dark arts like yul and huff or basic solidity optimization ?

Well, For me the answer is it depends, for fun i would like to optimize and juice out as much as i can using mystical arts like huff and yul. But i don't really know huff or yul. So i'll start off with basic over-the-head solidity optimizations.

Packing Variables :

To understand this, first, we must understand how storage work in solidity. In solidity, storage can be thought of as an array of size 2^256. And each section of this array is called a slot which can hold 256 bits/32 bytes.

Storage layout

Every time we declare a storage variable, the memory in the slot is assigned to the variable depending on the space it consumes. Eg: "unit256" takes up an entire slot of 32 bytes. Whereas uint8 only consumes 8 bits which is a byte of the slot.

uint8 roll;
uint256 id;
uint8 age;

The storage slot for the above would look like:

Here, even though the variable roll is only of 1 byte, the remaining 31 bytes are assigned to the variable because the next variable id requires 32 bytes, so it doesn't fit in the first slot therefore it takes up slot 2. Similarly, the age variable is stored in slot 3. Total memory cost for storing 3 variables becomes => 32 + 32 + 32 bytes = 96 bytes. More the memory, more the gas, more the cost.

To resolve this issue, we can arrange the variables so that as much as variables gets packed into a single storage slots as possible. For the above, we can first declare id which consumes the whole slot, then we can initialize roll and age which we can fit in a single slot.

uint256 id;
uint8 roll;
uint8 age;

Therefore, the memory consumed becomes = 32 + 32 => 64 bytes. Much cheap than the previous memory.

In later series we'll go more depth into other optimization techniques to reduce gas consumption.

9 Dangerous Techniques to Win Solidity Gas Optimization Contests

0
Subscribe to my newsletter

Read articles from Saksham Thapa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saksham Thapa
Saksham Thapa