TExcelTAD
Home › Solidity › Gas & Optimization

Gas & Optimization

Every EVM instruction costs gas. A transaction's fee is gas used × gas price, so inefficient code costs users real money, and code that needs more gas than a block allows can't run at all. This lesson shows where gas goes and how to measure it with gasleft().

What costs what

Operation Approximate gas
Arithmetic, comparisons, jumps 3–10
Reading memory / calldata 3 per word
keccak256 30 + 6 per word
Reading a storage slot (first time in a transaction, "cold") 2,100
Reading it again ("warm") 100
Writing a storage slot from zero to non-zero 22,100 (cold)
Changing an already non-zero slot ~5,000
Emitting an event 375 + 375 per topic + 8 per data byte
A plain ether transfer transaction 21,000 base cost
Deploying a contract 32,000 + 200 per byte of code

The headline: storage is expensive, everything else is cheap.

Measuring with gasleft()

gasleft() returns the gas remaining. The difference before and after a piece of code is what it cost:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    uint256 public stored;
    uint256 public other;                    // never written: its slot is still cold

    function main() external {
        uint256 g;

        g = gasleft();
        uint256 local = 42;
        local += 1;
        console.log("local arithmetic   :", g - gasleft());

        g = gasleft();
        stored = 42;                         // zero -> non-zero, cold slot
        console.log("first storage write:", g - gasleft());

        g = gasleft();
        stored = 43;                         // same slot again, in the same transaction
        console.log("second write       :", g - gasleft());

        g = gasleft();
        uint256 x = other;                   // cold read
        console.log("cold storage read  :", g - gasleft());

        g = gasleft();
        x = other;                           // warm read
        console.log("warm storage read  :", g - gasleft(), x + local);
    }
}
local arithmetic   : 272
first storage write: 22179
second write       : 179
cold storage read  : 2176
warm storage read  : 171 43

The second write is cheap because the slot was already written earlier in the same transaction (a "dirty" slot); writing a non-zero slot in a fresh transaction costs about 5,000 gas. Measurements include a few gas for the gasleft() calls and surrounding instructions, and the playground compiles without the optimizer, so they are slightly higher than the pure opcode prices. The ratios are what matter.

Cache storage reads

Reading the same storage variable in a loop pays for each read. Copy it into a local variable first:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    uint256[] public values;
    uint256 public multiplier = 3;

    function sumSlow() internal view returns (uint256 total) {
        for (uint256 i = 0; i < values.length; i++) {      // reads length every time
            total += values[i] * multiplier;              // reads multiplier every time
        }
    }

    function sumFast() internal view returns (uint256 total) {
        uint256 len = values.length;                      // read once
        uint256 m = multiplier;                           // read once
        for (uint256 i = 0; i < len; ) {
            total += values[i] * m;
            unchecked { ++i; }                            // i < len, so no overflow
        }
    }

    function main() external {
        for (uint256 i = 0; i < 20; i++) values.push(i);

        uint256 g = gasleft();
        uint256 a = sumSlow();
        uint256 slow = g - gasleft();

        g = gasleft();
        uint256 b = sumFast();
        uint256 fast = g - gasleft();

        console.log("results equal?", a == b);
        console.log("slow:", slow, "gas");
        console.log("fast:", fast, "gas");
    }
}
results equal? true
slow: 21810 gas
fast: 15694 gas

The slots are already warm when sumFast runs (the first loop touched them), which makes the comparison fair to sumSlow; the savings come from avoiding repeated SLOADs and checked increments.

Pack storage variables

The EVM reads and writes 32-byte slots. Small variables declared next to each other share a slot, so updating them together costs one write instead of several:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Loose {
    uint256 a; uint256 b; uint256 c;            // 3 slots
    function set() external { a = 1; b = 2; c = 3; }
}

contract Packed {
    uint64 a; uint64 b; uint64 c;               // 1 slot (24 of 32 bytes)
    function set() external { a = 1; b = 2; c = 3; }
}

contract Main {
    function main() external {
        Loose loose = new Loose();
        Packed packed = new Packed();

        uint256 g = gasleft();
        loose.set();
        console.log("3 separate slots:", g - gasleft());

        g = gasleft();
        packed.set();
        console.log("1 packed slot   :", g - gasleft());
    }
}
3 separate slots: 66853
1 packed slot   : 23315

Packing only helps when the values are read or written together. A lone uint8 is not cheaper than a uint256; the EVM even needs extra instructions to mask it.

More techniques

Technique Why it helps
calldata instead of memory for external array/string parameters avoids a copy
constant and immutable for fixed values no storage read at all (next lesson)
Custom errors instead of revert strings smaller bytecode and cheaper reverts
Events instead of storage for history logs cost a fraction of storage
Short-circuit cheap checks first in && / || skips expensive ones
Avoid unbounded loops keeps every function callable
unchecked { ++i; } in bounded loops skips overflow checks
Enable the optimizer (runs: 200 is common) the compiler removes redundancies

Tip: Measure before optimizing. Tools like forge test --gas-report and hardhat-gas-reporter show the gas used by every function. Readability and safety come first: an "optimization" that introduces a bug is the most expensive kind.

Test yourself

Which operation is by far the most expensive?

  1. Adding two numbers
  2. Reading calldata
  3. Writing a new non-zero value to a storage slot
  4. Calling a pure internal function

Why copy values.length into a local variable before a loop?

  1. It's required by the compiler
  2. To avoid reading storage on every iteration
  3. To make the loop run backwards
  4. Local variables can't overflow

When does packing small variables into one slot save gas?

  1. Always
  2. When they are read or written together
  3. Only for bool values
  4. Never; it costs more