New: Explore our latest Web3 innovations.Learn More about Ancilar Web3 services

Solidity Gas Optimisation: Storage, Packing, Assembly

Web3 Development
2024-01-02
Author:Jyotvir
Solidity Gas Optimisation: Storage, Packing, Assembly

Cut Solidity gas costs 30-60% using storage slot packing, struct layout, and Yul assembly. Audit-grade EVM storage patterns for Solidity engineers in 2024.

Frequently Asked Questions

Solidity storage slot packing is the compiler behaviour where multiple variables smaller than 32 bytes are placed into a single 32-byte storage slot. Each SSTORE or SLOAD operation costs gas per slot, not per variable, so fitting two uint128 values into one slot halves the I/O cost compared to two separate uint256 slots. Engineers control packing by ordering struct fields from smallest to largest type, or grouping sub-256-bit types consecutively. Correcting a four-field struct from naive to packed order can reduce cold SSTORE cost from 80,000 gas to 40,000 gas, with no assembly required and no change to the external ABI.
EIP-2929, activated at the Berlin hard fork in April 2021, introduced the concept of cold and warm storage access. A cold SLOAD now costs 2,100 gas and a cold SSTORE costs 20,000 gas for a zero-to-nonzero write. Once a slot is accessed within the same transaction it becomes warm, reducing subsequent SLOAD to 100 gas. Engineers can pre-warm slots using EIP-2930 access lists included in the transaction envelope, converting the first access from cold to warm pricing at a cost of 1,900 gas per storage key in the list. Break-even point is one cold SLOAD avoided per key.
Inline Yul assembly is justified when high-level Solidity generates demonstrably suboptimal opcodes on hot-path functions: tight loops over packed storage, bulk bitwise operations on packed booleans, or custom memory layouts for calldata decoding. The cost is auditor complexity and loss of static-analysis coverage. Ancilar applies Yul only after profiling shows measurable gas reduction on a representative transaction set, and only in functions that carry explicit NatSpec safety annotations. Any Yul block must be covered by invariant fuzz tests and reviewed as a separate, documented audit scope before deployment.

Don't Miss What's Next

Subscribe to newsletter

Tags:

Solidity

Gas Optimisation

Smart Contracts

EVM

Assembly

Storage Packing

Yul

Get in Touch

Our team will get back to you within 24 hours.

A clear proven process, that delivers

End of Scroll. Start of Discovery.

You've seen our ideas - now go deeper.
Discover more insights, tutorials, and innovations shaping Web3.