Gas Optimization
Gas is the fuel for the EVM. Every opcode costs a specific amount of gas. Optimization is the art of achieving the same logic with fewer or cheaper opcodes. This is critical because high gas costs can make DApps unusable.
Syntax Structure
Key Components
- Boilerplate structure required by the Solc compiler.
- Placement of state variables versus functions.
Practical Implementation
A comparison of standard vs optimized code.
Core Concepts
Cold vs Warm
First access to storage/account is expensive (Cold). Subsequent accesses are cheap (Warm).
Refunds
Freeing storage (setting to 0) used to give refunds, but now is capped.
Zero vs Non-Zero
Storing 0 is cheap. Storing non-zero is expensive.
Mental Model
The Toll Road
Driving a car (transaction). Every mile you drive costs gas. Turning on the AC (Storage) costs extra. Playing the radio (Memory) costs a little. The goal is to get to the destination carrying the same cargo, using the least fuel possible.
Under the Hood
Gas is calculated dynamically. `SSTORE` (20k/2.9k) and `SLOAD` (2.1k/100) are the main drivers. `unchecked` blocks disable overhead 0.8.0+ overflow checks.
Gas Analysis
The Holy Trinity of Savings.
- • Minimize Storage Writes.
- • Use `calldata` for read-only arguments.
- • Cache storage variables in memory/stack.
Security Risks
Optimization shouldn't compromise readability or security.
- ! Removing overflow checks (`unchecked`) blindly can cause massive bugs.
- ! Complex bit-packing can make code unmaintainable.
Common Use Cases
Interactive Visualization
See exactly how the EVM handles this code in memory, storage, and the stack.