What are the most impactful gas optimizations you reach for in a Solidity contract, and how do you decide they're actually worth it?
technical-conceptual · Senior level · software-engineering, blockchain-web3
What the interviewer is really asking
Assesses whether the candidate knows where EVM gas actually goes (storage dominates) and optimizes from measurement rather than folklore, with awareness of warm/cold access and calldata vs memory.
What to say
- State that storage operations dominate cost, so the biggest wins are minimizing SSTORE/SLOAD: pack variables into shared 32-byte slots, cache storage reads in local variables within a function, and avoid writing unchanged values.
- Explain warm vs cold access under EIP-2929 (a cold SLOAD is ~2100 gas versus ~100 warm), and use calldata instead of memory for external read-only array and struct arguments to skip the copy.
- Insist on measuring with a gas profiler or Foundry gas snapshots before and after, and weighing readability and audit risk, since a clever bit-packing that saves a few hundred gas can introduce a costly bug.
What to avoid
- Listing micro-tricks like 'use uint256 everywhere' or 'unchecked blocks' without grounding them in where gas is actually spent.
- Claiming variable packing always helps, ignoring that memory and function-local variables don't benefit and that packing can add masking overhead.
- Optimizing blind with no benchmark, or trading away readability and safety for negligible savings.
Example answers
Strong: I start from the fact that storage is the expensive resource, so I pack related small fields into one slot, cache a storage value in a local before looping over it, and skip writes that don't change the value. I lean on warm/cold access knowledge from EIP-2929 and use calldata for external array args to avoid the memory copy. Then I prove it with Foundry gas snapshots before and after, and I'll skip a packing trick if it hurts readability for a tiny saving, because audit time costs more than the gas.
Weak: I'd make all the variables uint256 since that's the EVM word size, wrap arithmetic in unchecked, and use shorter variable names. Those are the standard gas tricks so the contract ends up cheaper.