Skip to content
RED SAGSkills
mediumBlockchain Developer interview question

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.

Start mock interview

More medium Blockchain Developer questions