What techniques do you use to reduce gas costs in Solidity contracts?
What the interviewer wants to hear
- Minimise storage reads and writes; cache in memory
- Pack storage variables
- Use calldata, immutable and constant
- Custom errors instead of revert strings
- Avoid unbounded loops; use events instead of storage for logs
- Measure with gas reports and do not sacrifice security
Model answer
Storage is the most expensive part, so I start there. I read a storage variable once into a local variable instead of multiple times, and write only when the value actually changes. I pack small variables like uint64 and bool into the same 32-byte slot and order struct fields to fit. Values that never change are constant or immutable, which avoids storage reads. External function parameters use calldata instead of memory. I use custom errors instead of long revert strings, and emit events for data that only off-chain apps need instead of storing it. I avoid unbounded loops and use mappings over arrays when I do not need iteration. In tight loops with safe bounds, unchecked increments help a little. I always measure with forge snapshot or gas reports, and never trade away readability or security for tiny savings, especially since Layer 2 execution is already cheap.
Can you answer it under time pressure?
Take a timed medium round and get scored on every answer.
More medium Blockchain Developer questions
- What is a reentrancy attack and how do you prevent it?
- How do you test a smart contract before deploying it to mainnet?
- How do upgradeable smart contracts work, and what are the trade-offs?
- What is a blockchain oracle and how do you use price data safely?
- How do signature-based approvals like ERC-2612 permit and Permit2 work, and what are their risks?
- How do you build a reliable dApp frontend that reads and writes contracts with viem and wagmi?
- How do chain reorganizations affect a dApp or backend service, and how do you handle them?
- How do you design admin control for a protocol so it can be maintained without making users trust a single person?
- Walk me through how you deploy a set of contracts to mainnet safely.