r/solidity • u/block_intelligence • 4d ago
Storage packing only saves gas if the packed fields are touched together (and a couple other packing gotchas)
Some things about struct packing that I see people get wrong, mostly from reviewing contracts:
Packing saves gas when you read or write the fields in the same transaction. Two uint128 in one slot means one SLOAD or one SSTORE instead of two. But if you pack two variables that are updated in different functions, each write becomes a read-modify-write on the shared slot, since the EVM has to load the slot, mask in your new value, and store it back. In that case you can end up paying more than if they had their own slots. So pack by access pattern, not just by size.
Field order matters. Solidity packs in declaration order, so uint128, uint256, uint128 takes three slots, while uint128, uint128, uint256 takes two. Reordering a struct is free gas savings, but remember it changes the storage layout, so don't do it on an upgradeable contract without thinking hard about it.
Smaller types aren't cheaper outside storage. A uint8 local variable or function argument still lives in a 32 byte word, and the compiler may add masking ops to keep it clean. So uint8 everywhere for 'efficiency' often does nothing or costs slightly more. The savings come from storage slots.
The big costs are still the slot writes. Going from zero to nonzero is by far the most expensive case, and writing to an already nonzero slot is much cheaper. That's why some contracts keep a nonzero placeholder (like the reentrancy guard using 1 and 2 instead of 0 and 1).
Also, mappings and dynamic arrays don't pack their elements the way you might expect from a struct, and each mapping value starts at its own slot. Check with forge inspect <Contract> storageLayout rather than guessing, and use forge snapshot or gas reports to confirm a change really helped before you ship it.
Curious what other packing surprises people have hit.