Gas Optimisation — Web3

Measure, don't guess: npx hardhat test --gas-stats and the receipt's gasUsed, with the optimizer (runs: 200), which alone cuts RakaPoints's deploy from…

Search for "Solidity gas saving tips" and you'll find long lists. Some are stale, others don't apply to today's compiler. So the first rule of gas optimisation, making a contract need less gas to deploy and for every call so users pay less, is this: measure first. The costs at Raka's Shirt Shop make a good guide. Renting a permanent warehouse shelf is expensive (that's storage), a workbench cleared every night is cheap (that's memory), and the receipt a customer brings is only read, never filed (that's calldata). Saving gas is mostly about renting fewer shelves.

How to measure

Every number in this lesson was measured on the local Hardhat 3.19.0 chain with solc 0.8.37: gasUsed from each transaction's receipt, plus npx hardhat test --gas-stats. There are two build profiles:

// hardhat.config.ts
solidity: {
  profiles: {
    default: { version: "0.8.37" },
    production: { version: "0.8.37", settings: { optimizer: { enabled: true, runs: 200 } } },
  },
},

npx hardhat test --build-profile production uses the optimizer. The first saving needs no code change at all: deploying RakaPoints drops from 1,229,240 to 687,393 gas (44% cheaper). The numbers below use the production profile unless stated otherwise.

Storage, memory, calldata

Place Lives for Cost (today's EVM rules)
storage forever, on every node first read (cold) 2,100, later (warm) 100; write an empty slot 22,100, change a slot 5,000, rewrite the same slot in the same transaction 100
memory one call a few gas per operation
calldata one call, read-only a few gas per operation, no copying

Raka records Dinda's 10 purchases in uint256[] purchases and adds them into total:

// Version A: write storage every iteration
for (uint256 i = 0; i < purchases.length; i++) {
    total += purchases[i];
}

// Version B: add in a local variable, write storage once
uint256 sum = 0;
uint256 n = purchases.length;
for (uint256 i = 0; i < n; i++) {
    sum += purchases[i];
}
total = sum;

A = 72,604 gas, B = 69,487 gas: a saving of 3,117, not the "20,000 per iteration" of old tips. Once touched, the total slot is warm and a rewrite costs only 100 gas. For an array parameter, calldata (47,220) is cheaper than memory (48,205) because nothing is copied; use calldata for external parameters you don't change.

Struct packing

Storage is split into 32-byte slots. Small variables written next to each other share a slot. Field order decides everything (layout from solc's storageLayout):

struct LooseCustomer {    // 3 slots
    uint128 points;  // slot 0, bytes 0-15
    uint256 id;      // slot 1
    uint128 spent;   // slot 2
}

struct PackedCustomer {   // 2 slots
    uint128 points;  // slot 0, bytes 0-15
    uint128 spent;   // slot 0, bytes 16-31
    uint256 id;      // slot 1
}

After register(Dinda, 1, 160 PTS, $160), slot 0 of the packed version (read with eth_getStorageAt) holds two values at once: 0x00000000000000000000000000003e80 0000000000000008ac7230489e800000. The left 16 bytes = 0x3e80 = 16,000 (spent, in cents), the right 16 bytes = 160 × 10^18 (points). A new registration: 89,043 becomes 66,903 gas (22,140 saved, one fresh slot write). Changing the data: 34,955 becomes 29,915.

Custom errors vs require strings

require(balance >= amount, "Not enough PTS balance for redeeming");  // A
if (balance < amount) revert NotEnoughPoints(balance, amount);       // B
require(balance >= amount, NotEnoughPoints(balance, amount));        // C, since solc 0.8.27
A string B custom error C require + error
runtime bytecode 425 bytes 376 bytes 380 bytes
deploy gas 145,219 134,583 135,459
gas of the reverted transaction 23,801 23,765 23,768

The biggest saving is in contract size and deploy cost; on a revert it's only 36 gas. The main reason to use custom errors is something else: they carry data (balance, amount) that viem can read.

Events vs storage

Recording purchase history in a storage array: 88,371 gas for the first entry. Emitting the event Purchase(customer, cents): 23,331. That saves 65,040, because an event only goes into the receipt's log, not into storage. The condition: other contracts can't read events. Use events for history a frontend or an indexer reads, storage for data the contract's logic uses.

immutable and constant

address public immutable owner;                  // baked into the bytecode at deploy
uint256 public constant CENTS_PER_POINT = 100;   // baked in at compile time

An earn that reads owner and centsPerPoint from storage: 48,520 gas. With immutable and constant: 44,343, because two cold storage reads (2 × 2,100) disappear. Deploy drops too, from 206,645 to 172,683. This saving costs no readability: use it for values that never change.

unchecked: when it's safe, when it does nothing

Since Solidity 0.8, + and - are checked for overflow. unchecked { } turns the check off. A popular tip says to swap i++ in a loop for unchecked { ++i; }. Before you look at the table, guess: with solc 0.8.37 and the optimizer on, how much gas does that save? About 80 per iteration, about 500 in total, or zero?

Change Optimizer off Optimizer on
i++ to unchecked { ++i; } in a 10-iteration loop 70,727 to 70,677 69,487 to 69,487
balance - amount after if (balance < amount) revert 27,096 to 26,917 26,744 to 26,677

Swapping i++ in a loop saves zero gas: since solc 0.8.22 the compiler itself drops the overflow check on a simple loop counter. The subtraction after a check saves 67 gas and is safe, because the line before proves balance >= amount; OpenZeppelin's ERC20 does exactly that. Without a proof like that, unchecked turns an overflow into a silent bug.

🤔 When optimisation isn't worth it

A sensible order: turn on the optimizer, write storage less (events, local variables), pack structs that are written often, immutable/constant. After that, weigh every trick against its cost: harder-to-read code is harder to audit, and a contract bug costs far more than 67 gas. Inline assembly or bitwise tricks for an admin function called once a month are almost never worth it.

⚠️ Gas tips that backfire

TL;DR: Measure, don't guess: npx hardhat test --gas-stats and the receipt's gasUsed, with the optimizer (runs: 200), which alone cuts RakaPoints's deploy from 1,229,240 to 687,393. The biggest savings come from fewer SSTOREs: events instead of storage (88,371 to 23,331), variable packing that puts small fields next to each other in a 32-byte slot (89,043 to 66,903), and writing storage once at the end of a loop (3,117 saved, because a warm slot costs only 100 gas). calldata is cheaper than memory for parameters, immutable/constant remove storage reads (4,177 saved), custom errors shrink bytecode (425 to 376 bytes) and carry data. unchecked { ++i; } saves zero gas since solc 0.8.22; unchecked is worth it only after a check that proves it's safe. If a trick hurts readability for a few dozen gas, skip it.

⚡ Measure first, then save

Meaning: Use npx hardhat test --gas-stats and the receipt's gasUsed. The optimizer alone (runs: 200) cuts RakaPoints's deploy from 1,229,240 to 687,393 gas.

⚡ Variable packing

Write:

struct PackedCustomer {   // 2 slots
    uint128 points;  // slot 0, bytes 0-15
    uint128 spent;   // slot 0, bytes 16-31
    uint256 id;      // slot 1
}

Meaning: Small variables written next to each other share one 32-byte slot. uint128, uint256, uint128 takes 3 slots; uint128, uint128, uint256 takes only 2.

⚡ Write storage less

Meaning: Events replace storage for history (88,371 becomes 23,331 gas), but other contracts can't read events. immutable and constant remove storage reads.

⚡ unchecked in a loop

Guess first: with solc 0.8.37 and the optimizer on, how much gas does swapping i++ in a loop for unchecked { ++i; } save?

Zero. Since solc 0.8.22 the compiler itself drops the overflow check on a simple loop counter.

Meaning: unchecked is worth it only after a check that proves it's safe, such as balance >= amount before a subtraction.

What you will learn