2

do you have any cheat sheet in order how the variables should be ordered to achieve best possible packing and to be more gas efficient

For example I know bool takes 8 bits, address takes 20 bytes but what is the correct order for all do you have any idea? Thanks in advance!

1 Answer 1

2

The EVM operates on a 256 bits basis, so you need to order variables to fit in 256 bits.

Unpacked variables:

uint128 a; // 128 bits => fills one slot => 256 bits
uint256 b;
uint128 c; // 128 bits => fills one slot => 256 bits

Packed variables:

uint128 a;
uint128 c; // 128 + 128 = 256 bits
uint256 b;

The first example is not gas efficient since 3 slots will be used to store the data, while the second will only need 2 slots.

Source: https://www.maxgrok.com/posts/saving-gas-with-packing-in-solidity

2
  • Shared source link is dead.
    – alper
    Dec 11, 2022 at 21:13
  • @alper Thanks for flagging. It's now back up.
    – Pierrick
    Jan 7, 2023 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.