Estimating and Optimising Gas
Gas costs are paid by every user of a contract, so measuring and reducing them is part of good design. This lesson explains how to estimate and measure gas with tools, then covers the optimisation techniques that matter most and the ones to avoid.
Learning outcomes
After completing this lesson, you will be able to:
- Explain how eth_estimateGas works and when it fails.
- Describe tools for measuring gas.
- Choose effective gas optimisation techniques.
- Identify optimisations that compromise safety.
Estimating gas
eth_estimateGas simulates a transaction against the current state and returns the gas it would use. web3.js exposes it as web3.eth.estimateGas(tx) and contract.methods.fn(args).estimateGas({ from }). Wallets call it before every transaction and add a margin. Two behaviours are worth knowing: if the simulated transaction would revert, estimation fails with the revert reason, warning the user before they pay; and if state changes between estimation and inclusion, actual usage can differ, especially for functions with loops or branches that depend on state.
How estimation works
Measuring gas during development
The following tools measure real gas usage.
- Hardhat gas statistics
npx hardhat test --gas-statsprints minimum, average, median and maximum gas per function called in tests, deployment gas and bytecode size.- Remix
- The terminal shows transaction cost and execution cost for every transaction in the Remix VM; the debugger shows gas per opcode.
- Receipts
gasUsedandeffectiveGasPricegive the actual cost of any mined transaction.- Foundry
forge test --gas-reportand gas snapshots compare costs between versions.
Running gas reports in continuous integration catches regressions: a change that makes a common function 20% more expensive is visible before deployment.
Optimisation techniques
Most savings come from reducing storage access. The following table lists the techniques with the biggest effect.
| Technique | Why it saves gas |
|---|---|
| Pack small variables into one slot | One SSTORE or SLOAD serves several variables |
| Use constant and immutable | Values live in bytecode; no SLOAD at run time |
| Cache storage reads in local variables | One cold SLOAD instead of repeated reads in loops |
| Use calldata for read-only external parameters | Avoids copying into memory |
| Use custom errors | Smaller bytecode and cheaper reverts than strings |
| Emit events for off-chain data | Logs cost far less than storage |
| Avoid unbounded loops | Keeps gas bounded and prevents denial of service |
| unchecked for provably safe arithmetic | Skips overflow checks, for example on a bounded loop counter |
| Enable the optimizer with suitable runs | Applies many low-level optimisations automatically |
// Unpacked: three slots
uint256 a; // slot 0
uint256 b; // slot 1
uint256 c; // slot 2
// Packed: one slot (16 + 8 + 8 = 32 bytes)
uint128 a;
uint64 b;
uint64 c;Packing only helps when the variables are declared next to each other and are read or written together; a lone uint8 can even cost slightly more than a uint256, because the EVM must mask the smaller value.
A gas-hungry function
What not to optimise
Safety first
Never trade safety for gas. Removing input checks, using unchecked where overflow is possible, replacing audited library code with hand-written assembly, or skipping reentrancy protection can save a few hundred gas and lose everything the contract holds. Optimise after the code is correct, tested and reviewed, and measure every change.
When to stop optimising
Caching in a loop
A function loops 100 times and reads the state variable feeRate in each iteration. How much gas does caching it in a local variable save?
Without caching, the first read is cold (2,100 gas) and the next 99 are warm (99 × 100 = 9,900), about 12,000 gas in total. With uint256 rate = feeRate; before the loop, there is one cold read of 2,100 gas and then cheap stack reads of about 3 gas each, saving close to 10,000 gas per call. If feeRate never changes after deployment, making it immutable removes even the first read.
A reverting estimate
A DApp's "Buy" button shows the error "cannot estimate gas; transaction may fail" and the wallet never opens. What should the developer investigate?
Gas estimation simulates the transaction, and the simulation reverted. The developer should read the revert reason in the error (for example, an insufficient allowance, a sale that has not started or a missing value) rather than forcing a fixed gas limit. Forcing a limit would only send a transaction that reverts on chain and charges the user for nothing.
Name the optimisation that stores several small variables in one storage slot.
Show answer
Variable packing: declaring variables smaller than 32 bytes next to each other, such as a uint128 and two uint64s, so they share one slot and are read or written together.
Exam Tips
Remember for the exam
- estimateGas simulates; a failed estimate usually means the transaction would revert.
- Measure with npx hardhat test --gas-stats, Remix and receipts.
- Biggest savings: fewer storage reads and writes (packing, caching, constant, immutable).
- Never remove checks or protections to save gas.