Smart-contract development

gas optimization

Every operation on Ethereum costs gas, and persistent storage is by far the most expensive resource. Gas optimization is therefore mostly the art of touching storage as little as possible, and doing arithmetic and data handling in the cheaper way. Done well it can cut a transaction's cost by a large fraction; done blindly it can wreck readability for trivial savings.

The high-impact techniques cluster around storage. Pack several small variables into one 32-byte slot so a single SSTORE updates them all. Cache a storage value in a memory or stack variable before reading it repeatedly in a loop — a cold SLOAD is about 2,100 gas and a warm one about 100, while a cold SSTORE turning a zero slot non-zero is about 20,000 gas. Use constant and immutable for values fixed at compile or construction time, since they are baked into the bytecode and cost no storage at all. Prefer calldata over memory for external function array arguments to skip a copy, and use custom errors instead of long revert strings (a 4-byte selector versus many bytes).

On the arithmetic and control side: since Solidity 0.8 inserts automatic overflow checks, wrap provably-safe math (like a loop counter) in an unchecked block to skip them. Avoid loops over unbounded arrays — their gas grows with length and can hit the block gas limit, which is also a denial-of-service risk if an attacker can grow the array. Use bitmaps for sets of boolean flags, and consider transient storage (EIP-1153's TSTORE/TLOAD) for values needed only within a single transaction, such as a reentrancy lock. Above all, measure: a gas profiler tells you which storage writes actually dominate, so you optimize the costly 5% instead of obscuring the cheap 95%.

uint128 a; uint64 b; uint64 c;   // these three share ONE 32-byte slot
error Unauthorized();            // cheaper than require(.., "string")
for (uint256 i; i < n;) {
  total += data[i];
  unchecked { ++i; }             // counter can't overflow: skip the check
}

Spend gas where it matters; storage is the budget.

The rule of thumb: storage dwarfs everything. One avoided cold SSTORE (~20,000 gas) outweighs thousands of arithmetic micro-optimizations — profile before you obfuscate.