← all simulations

slide 24 · contracts

Advanced contract writing

naive
88k gas
packed
31k gas

costs, vs memory, mappings, inheritance and custom errors.

  1. 1Toggle the gas optimisations
  2. 2Compare gas before and after
  3. 3Apply the checks-effects-interactions order
live · 0 players in this room

send coins to another player

10.0000 BTC10.0000 ETH
recipient

waiting for another player to join this room… open this page in a second tab or share the link with the class.

fee 0.0005 · total 0.5005 BTC
live transfers in this room
room ledger · tap a row to replay its steps
  • no transfers yet — be the first to pay a classmate.
Naive cost
63,000 gas
Optimised cost
23,160 gas
Saving
63%

Naive version

1function sum() external view returns (uint256 t) {
2 for (uint i = 0; i < items.length; i++) {
3 t += items[i]; // SLOAD every iteration
4 }
5}

Improved version

1function sum() external view returns (uint256 t) {
2 uint256[] memory local = items; // one copy
3 uint256 len = local.length; // cached
4 for (uint i; i < len; ++i) {
5 t += local[i]; // MLOAD, ~100x cheaper
6 }
7}

Why

An SLOAD costs 2,100 gas cold; an MLOAD costs 3. Reading array length inside the loop condition is a storage read on every pass. Copy to memory once, cache the length, and use ++i rather than i++ to skip a temporary.

Advanced is mostly two disciplines: knowing what each opcode costs, and assuming every external call is hostile. Test with Foundry fuzzing, measure with snapshots, and get an audit before holding real value.