๐ ๏ธ Code Optimization: Loops & Memory
Learn gas-efficient patterns for common operations
Write efficient smart contracts that save money
Your Progress
0 / 5 completed๐ Code-Level Optimizations
Beyond storage, code structure matters. Loop optimization is criticalโcaching array.length saves 2,100 gas per iteration; using ++i instead of i++ saves 5 gas (no temp variable); wrapping in unchecked saves 100+ gas (skip overflow checks). Short-circuiting leverages && and ||โput cheap checks first (local vars) before expensive ones (storage reads). Unchecked math (Solidity 0.8+) removes automatic overflow checks when you've manually verified safety. Function modifiers copy code into each functionโif a modifier reads storage, inline it or cache the value. These micro-optimizations compound: a 100-iteration loop with all techniques applied saves 30,000+ gas.
๐ฎ Interactive: Before & After Comparison
Select an optimization technique to see inefficient vs optimized code side-by-side with gas savings explained.
Loop Optimization
30-50% savingsCache length, use ++i instead of i++, avoid storage in loops
// โ BAD: Expensive loop
for (uint i = 0; i < array.length; i++) {
total += array[i];
// SLOAD on length each iteration
// i++ creates temporary variable
}// โ
GOOD: Optimized loop
uint len = array.length; // Cache
uint _total = total; // Cache storage
for (uint i; i < len; ) {
_total += array[i];
unchecked { ++i; } // Cheaper increment
}
total = _total;Caching array.length saves SLOAD per iteration (2,100 gas each). ++i is 5 gas cheaper than i++ (no temp variable). Unchecked saves overflow check (Solidity 0.8+).
๐ง Advanced Loop Techniques
for (uint i = len; i > 0; ) { unchecked { --i; } } saves gas vs forward (comparison to 0 is cheaper than to variable).x += a[0]; x += a[1]; x += a[2]; vs loop. Saves loop overhead.break or return as soon as condition met. Don't iterate remaining elements unnecessarily.โก Short-Circuit Cheat Sheet
require(amount > 0 && balance[msg.sender] >= amount && isWhitelisted(msg.sender))๐ข When to Use Unchecked
- โข Loop counters (bounded by known length)
- โข Decrement after require check
- โข Increment where max is type limit
- โข Array index iteration (length is bound)
- โข User-provided arithmetic
- โข Token amounts (transfers, balances)
- โข Reward calculations
- โข Price conversions
๐ก Quick Wins
- โขUse
!= 0instead of> 0: Costs 6 less gas (no GT opcode). - โขUse
bytes32overstring: Fixed-size types are cheaper. Convert strings to bytes32 when possible. - โขUse
calldatafor read-only arrays: Cheaper thanmemoryfor function parameters (no copy). - โขUse
privateoverpublic: Public creates automatic getter (costs deployment gas).