Five Smart Contract Gas Optimization Patterns That Actually Matter in 2026
Gas costs on Ethereum mainnet swing between 5 and 50 gwei. For any protocol handling real volume, the difference between a naive contract and an optimized one is thousands of dollars per month in user fees. This article breaks down five patterns that compound, with the measured savings for each.
1. Packed Structs: One Slot Instead of Three
The EVM stores state in 32-byte slots. A cold SLOAD costs 2100 gas; a warm one 100. Declare small variables together and the compiler packs them.
Instead of three uint256 (three slots, three cold reads), use uint128 a; uint128 b; uint256 c; — two slots. On a function that reads all three, that is one avoided cold SLOAD: 2100 gas saved per call.
2. Constant and Immutable Over Storage
constant values live in bytecode and cost 3 gas to read. immutable values are written once at construction and read from code. Both beat a storage read by 2097 gas. A contract with 20 constants referenced in a hot loop saves ~42,000 gas per transaction.
3. Custom Errors
Since Solidity 0.8.4, error InsufficientBalance(uint256 available, uint256 required); replaces require(..., "string"). The revert string is stored in memory and ABI-encoded; a custom error is a 4-byte selector. Measured saving: 200-500 gas per revert path, and smaller bytecode.
4. Unchecked Blocks
The overflow check on each arithmetic op is ~20-40 gas. In a loop incrementing a counter that provably cannot overflow, wrapping the body in unchecked { ... } removes that check every iteration. A 1000-iteration loop saves 20,000-40,000 gas.
5. Short-Circuit Ordering
&& and || short-circuit. Put the cheapest, most-likely-to-fail condition first: require(amount > 0 && balance >= amount). Reordering two conditions in a hot function saves the cost of the second check on the common revert path.
Measured Impact
Across a representative DeFi contract (deposit, withdraw, transfer), these five patterns together cut runtime gas 20-40% and bytecode size 10-15%. The only reliable method is to benchmark before and after with Foundry forge test --gas-report or Hardhat gas reporter. Optimize what the report shows, not what you assume.