Gas optimization
Gas is the fee for running code, paid in ETH. Every operation has a gas cost, and storage operations are by far the most expensive. Writing a new storage slot costs about 20,000 gas, while adding two numbers costs only a few gas.
The biggest savings come from touching storage less. Cache a storage value in a local variable when you use it more than once. Mark values constant or immutable when they never change, so they are read from the code instead of storage.
Storage is organized in 32-byte slots. Small types such as uint128, uint64, bool and address can share a slot when declared next to each other, which is called packing. Packing saves gas when the fields are read and written together, but it can cost more when they are not.
Other savings: use calldata instead of memory for read-only external inputs, use custom errors instead of long revert strings, and emit events instead of storing data that only the frontend needs. Use unchecked blocks for math that cannot overflow, such as a loop counter, but only when you are certain.
Measure before you optimize. Foundry's gas reports and forge snapshot show exactly which functions cost the most. Never trade safety or readability for tiny savings, because a gas bug is cheaper than a security bug.
contract Gas { uint256 public constant FEE = 100; // inlined, no storage read address public immutable owner; // set once in the constructor struct Packed { // fits in one 32-byte slot uint128 amount; uint64 start; uint32 duration; bool active; } Packed public deal; uint256[] public items; error NotOwner(); constructor() { owner = msg.sender; } function setDeal(uint128 a, uint32 d) external { if (msg.sender != owner) revert NotOwner(); deal = Packed(a, uint64(block.timestamp), d, true); } function add(uint256[] calldata xs) external { for (uint256 i = 0; i < xs.length; i++) items.push(xs[i]); } function total() external view returns (uint256 t) { uint256 n = items.length; // cache the length for (uint256 i; i < n;) { t += items[i]; unchecked { i++; } // i cannot overflow here } } }
Try it yourself
Reorder the Packed struct so that a uint256 sits between two small fields, compile it, and work out how many storage slots it now uses. In the Testing module you can compare the cost with forge snapshot.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.