Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 47 ยท Security

Gas Costs and Optimization

Understand what makes Solidity transactions expensive: storage writes, packing, calldata, loops and custom errors, and measure savings with a gas-counting model.

Every operation the EVM runs costs gas, and you pay for gas in ether. A cheap function is a gift to your users; an expensive one can make a contract unusable when the network is busy. Gas also matters for correctness: a function that loops over a growing list will one day exceed the block gas limit and become impossible to call (see Common Vulnerabilities).

This lesson explains where gas goes, which habits save the most, and how to measure instead of guess. The numbers quoted are approximate and are taken from the rules in force at the time of writing; the exact schedule changes between network upgrades, so treat them as orders of magnitude and check your own tests for real values.

Where the gas goes

Storage writes By far the most expensive thing you do.
Storage reads Cheaper, but cold reads still add up.
Memory Cheap at first, quadratic when large.
Calldata Pay per byte you send in.
1 / 2

The cost of storage

Persistent storage is shared by every node forever, and the price reflects that. Rough figures for the current rules:

  • Every transaction pays a base fee of 21,000 gas before any code runs.
  • Writing a storage slot from zero to non-zero costs about 20,000 gas. Changing a slot that already holds a value costs about 2,900.
  • The first read of a slot in a transaction (a "cold" read) costs about 2,100, and later reads of the same slot (a "warm" read) cost about 100.
  • Memory reads and writes and basic arithmetic cost about 3 gas each.

Storage is hundreds or thousands of times more expensive than anything else, so the biggest savings come from touching it less. Review Storage, Memory and Calldata for what lives where.

A gas counter you can run

The stand-in below is a simplified meter, not the real EVM. It applies the cold/warm rules above, charges 20,000 for a first write to an empty slot, 2,900 for a change, 100 for rewriting a slot already changed in the same call, and ignores refunds. Two versions of the same loop add up ten stored numbers.

JS Naive loop vs cached loop

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Both versions reach the same total. The cached one reads count and sum once, keeps the running total in a local variable, and writes the result once. The saving looks modest here because the ten cold reads of the items cost the same either way; what you can remove is the repeated access to count and sum. In real code the equivalent is uint256 len = items.length; before a loop and a local accumulator instead of repeated storage updates.

Packing variables

Storage is organized in 32-byte slots, and the compiler packs neighbouring small variables into one slot when they fit. Two uint128 values share a slot; a uint128, a uint64 and an address (20 bytes) do not all fit into one, because 16 + 8 + 20 is 44 bytes. Order matters, as does choosing no wider a type than you need.

SOLIDITY
struct Wasteful {   // three slots
    uint128 a;
    uint256 b;      // needs a whole slot, so a sits alone
    uint128 c;
}

struct Packed {     // two slots
    uint128 a;
    uint128 c;      // shares a slot with a
    uint256 b;
}

Packing helps when you write several fields together, because one slot write replaces several. It can hurt when you read or write one small field alone, since the compiler adds masking and shifting. Packing standalone uint256 values buys nothing. Storage, Memory and Calldata shows how slots are computed.

JS One slot or two

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Other habits that add up

calldata instead of memory for read-only external parameters. An external function with uint256[] calldata ids reads the arguments straight from the transaction data. With memory, the contract first copies the whole array into memory. If the function only reads the array, the copy is wasted (Strings, Bytes, Arrays and Structs).

Memory is cheap until it is not. Memory has a linear price plus a quadratic term, so doubling a large array costs much more than twice as much. The formula is 3 * words + words * words / 512:

JS Memory cost grows quadratically

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Custom errors instead of long revert strings. require(x, "Insufficient balance for this operation") stores the text in the contract and returns it in the revert data. A custom error (Control Flow, require, revert and Custom Errors) is identified by a 4-byte selector, which makes deployment smaller and reverts cheaper, and it can still carry parameters.

SOLIDITY
error InsufficientBalance(uint256 have, uint256 need);   // 4-byte selector + parameters

if (balance < amount) revert InsufficientBalance(balance, amount);

constant and immutable values are baked into the bytecode and cost no storage reads (Constructors, Constants and Immutables).

Loops. Anything repeated multiplies its per-iteration cost. Keep loop bodies free of storage access, cache the length, and never loop over data that users can grow without limit. Use a mapping and a counter instead of scanning an array.

unchecked blocks skip the 0.8 overflow checks and save a small amount per operation. Use them only where you can prove the arithmetic cannot overflow (for example i++ in a loop bounded by length); recent compilers (0.8.22 and newer) already skip the check for simple bounded loop counters, so the trick matters less than it used to.

Short-circuit and order checks. Put cheap checks (comparing arguments) before expensive ones (reading storage, external calls), so that failing calls fail early.

Transient storage. Recent network upgrades added storage that is wiped at the end of each transaction and costs about 100 gas per access. It suits temporary data such as a reentrancy lock; the details depend on the compiler version you use.

Do not trade safety for gas. Removing a check, skipping validation, or hand-written assembly to save a few hundred gas has caused real losses. Optimize hot paths that you have measured, and keep the readable version when the saving is small.

Measure, do not guess

Gas intuition is often wrong, and compilers keep improving. Use the tools:

Terminal
forge test --gas-report            # gas used by each function in your tests (Foundry)
forge snapshot                     # record gas per test, then diff after a change
forge inspect MyContract storageLayout   # see how variables map to slots

In Hardhat, the hardhat-gas-reporter plugin prints a similar table. The Solidity compiler's optimizer (optimizer.enabled with a runs setting) trades deployment size against per-call cost: a low runs value favours smaller bytecode, a high value favours cheaper calls. The via-IR pipeline can produce better code but compiles more slowly. Always compare before and after on your own tests.

Here is a tiny comparison of revert data sizes, which determines part of the cost of failing calls:

JS Revert data: string vs custom error

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the cost rules described above (up to network upgrades) and the quadratic memory formula. Stand-in: the Meter leaves out refunds, access lists and most opcodes, so use it to see the shape of the savings, not to predict your bill.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which operation is by far the most expensive in typical Solidity code?

    A first write to an empty slot costs about 20,000 gas, thousands of times more than arithmetic or memory access.
  2. 2. Why cache items.length and running totals in local variables before a loop?

    Repeated storage access multiplies the cost by the number of iterations. Keep working values in memory or on the stack and write the result once.
  3. 3. When does packing two uint128 fields into one slot help most?

    Packing saves slot writes when fields are updated together. Touching a single small field can cost extra for masking and shifting.
  4. 4. What is the main gas advantage of a custom error over require(cond, "long text")?

    Custom errors reduce deployment size and the size of the data returned when the call fails.

Summary

  • Gas is the price of computation; storage writes dominate it, then cold storage reads.
  • Read a slot once, work in memory, write the result once.
  • Pack fields that are written together, use calldata for read-only external parameters and prefer custom errors to long revert strings.
  • Memory cost grows quadratically; avoid unbounded loops and huge arrays.
  • Use unchecked only with a proof, and never trade safety for small savings.
  • Measure with forge test --gas-report, snapshots and your own tests, because costs change between compiler and network versions.

Next: Testing Contracts.