Blockchain & Smart Contracts

Solidity Gas Optimization: Five Changes That Actually Matter

Five common Solidity gas tips, each measured on Hardhat 3 with and without the optimizer: constants and immutables, struct packing, cached array length, calldata, and the unchecked loop counter that no longer matters.

By Rajib Roy Published 5 min read

Search for "Solidity gas optimization" and you'll find lists of dozens of tricks. Some save real money, some save pocket change, and a few are obsolete since the compiler learned to do them for you. Most of those lists don't show a single measurement, so it is hard to tell which is which.

I picked five of the most repeated tips and measured them on a small contract with Hardhat 3, with the compiler optimizer off and on. The result is a ranked list with numbers, and a clear verdict on the one that is no longer worth your attention.

How I measured

One contract, GasLab, contains both versions of each change. A test calls each function and prints the gas used. For state-changing functions, I read the gas from the transaction receipt. For read-only functions, I used estimateGas, which includes the 21,000 base cost of any transaction. I ran the test twice: once with Hardhat's default build profile (no optimizer) and once with the production profile (optimizer on, 200 runs).

GasLab.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract GasLab {
    // --- 1. constant / immutable vs a storage variable --------------------------------------
    uint256 public feeStorage = 30;
    uint256 public immutable FEE_IMMUTABLE = 30;
    uint256 public constant FEE_CONSTANT = 30;
    uint256 public out;

    function useStorage(uint256 x) external { out = x * feeStorage; }
    function useImmutable(uint256 x) external { out = x * FEE_IMMUTABLE; }
    function useConstant(uint256 x) external { out = x * FEE_CONSTANT; }

    // --- 2. struct packing --------------------------------------------------------------------
    struct Unpacked { uint256 a; uint256 b; }
    struct Packed { uint128 a; uint128 b; }
    Unpacked public unpacked;
    Packed public packed;

    function writeUnpacked() external { unpacked = Unpacked(1, 2); }
    function writePacked() external { packed = Packed(1, 2); }

    // --- 3. reading storage in a loop ----------------------------------------------------------
    uint256[] public data;

    function fill(uint256 n) external { for (uint256 i; i < n; i++) data.push(i); }

    function sumReadLength() external view returns (uint256 s) {
        for (uint256 i; i < data.length; i++) s += data[i];
    }

    function sumCachedLength() external view returns (uint256 s) {
        uint256 len = data.length;
        for (uint256 i; i < len; i++) s += data[i];
    }

    // --- 4. calldata vs memory for external array parameters ----------------------------------
    function sumMemory(uint256[] memory xs) external pure returns (uint256 s) {
        for (uint256 i; i < xs.length; i++) s += xs[i];
    }

    function sumCalldata(uint256[] calldata xs) external pure returns (uint256 s) {
        for (uint256 i; i < xs.length; i++) s += xs[i];
    }

    // --- 5. "unchecked" loop counter ------------------------------------------------------------
    function loopChecked(uint256 n) external pure returns (uint256 s) {
        for (uint256 i; i < n; i++) s += i;
    }

    function loopUnchecked(uint256 n) external pure returns (uint256 s) {
        for (uint256 i; i < n; ) {
            s += i;
            unchecked { ++i; }
        }
    }
}

The rest of the setup, the measuring test, is in the same folder and simply prints the results. It has no assertions on purpose: it is a measuring tool, not a specification.

The results

MeasurementNo optimizerOptimizer, 200 runs
Read a storage variable29,01028,665
Read an immutable24,13423,786
Read a constant24,15623,808
Write a struct of 2 × uint25665,58265,539
Write a struct of 2 × uint12843,82243,388
Loop that re-reads data.length155,388148,850
Loop that caches data.length150,000143,859
Memory array parameter, 100 items89,17762,206
Calldata array parameter, 100 items66,61256,830
Checked loop counter, 100 iterations46,78833,878
Unchecked loop counter, 100 iterations46,30833,898

Now let's read it tip by tip.

1. Use constant and immutable instead of storage (worth it)

A value that never changes shouldn't live in storage. Reading a storage variable costs a storage read; a constant is baked into the code, and an immutable is set once in the constructor and then also baked into the code. In my test, a function reading a storage variable used 29,010 gas without the optimizer, against 24,134 for the immutable and 24,156 for the constant, a saving of roughly 4,900 gas per call, about 17%. With the optimizer on, the gap was similar (28,665 vs 23,786 and 23,808). This is the easiest win in the list: no tradeoff, and it makes your intent clearer. Anything fixed at deployment, like a fee, a token address or an owner set in the constructor, should be one of the two.

2. Pack your structs (big, when you write a lot)

Storage is organised in 32-byte slots. Two uint128 values fit in one slot, so writing them costs one storage write; two uint256 values need two. Writing a fresh struct from zero cost 65,582 gas with two uint256 fields, and 43,822 with two uint128 fields, a saving of about 21,800 gas, or a third. With the optimizer, it was 65,539 against 43,388. The optimizer doesn't pack storage for you. Because writing a new storage slot is one of the most expensive operations, this is where the largest savings live. The cost is that you must be sure the smaller types are big enough for your values, which is a correctness risk, not just a style choice. Pack things that are written together, and don't shrink a variable that you'll often convert back and forth.

3. Cache storage reads outside loops (small, but free)

Reading data.length in every loop iteration reads storage every time. Copying it into a local variable once avoids that. Over a 50-item array, the saving was about 5,400 gas without the optimizer (155,388 vs 150,000) and about 5,000 with it (148,850 vs 143,859), around 3%. That's modest because storage reads of already-touched slots are cheaper than first reads. It still costs you nothing but one line, and the saving grows with the loop. More importantly, caching also helps correctness: you iterate over a stable bound.

4. Use calldata for external array parameters (good, sometimes large)

An external function that takes an array can declare it calldata, which reads directly from the transaction data, instead of memory, which copies it first. For a 100-item array, the memory version cost 89,177 gas without the optimizer, against 66,612 for calldata, a drop of about 25%. With the optimizer on, the gap shrank to 62,206 vs 56,830, about 9%. So the tip is real, and the optimizer already recovers a large share of the difference, which is why you should measure with your production settings and not trust a number from an unoptimized build. Use calldata whenever the function doesn't modify the array. The tradeoff is that you can't change a calldata array in place.

5. The "unchecked" loop counter (no longer worth it)

For years, advice said to wrap the loop counter increment in unchecked { ++i; } to skip the overflow check. Since Solidity 0.8.22, the compiler does this on its own for simple loops of the form for (uint i; i < n; i++), and the release announcement says the optimization is enabled even when the rest of the optimizer is switched off. My numbers agree: without the optimizer, the manual version saved 480 gas out of 46,788 (about 1%), and with the optimizer the "unchecked" version was in fact 20 gas worse (33,898 vs 33,878). That's noise. The manual pattern makes your code harder to read for no gain, and removing the overflow check by hand creates a risk if you later change the loop. Write the plain loop, and save unchecked for places where you've proven that overflow is impossible and where the saving is large.

What matters more than any of these

  • Storage writes dominate. The biggest savings come from not writing storage: fewer slots, fewer updates, events instead of storage for data nobody needs on-chain.
  • The optimizer matters, and so does the build profile. Deploy with the optimizer on, and measure with the same settings. In several rows above the optimizer saved more than the "trick" did.
  • Algorithmic cost. A loop over an unbounded array is both a gas problem and a denial-of-service risk. Design so that no function's cost grows without limit.
  • Readability and safety. Saving 400 gas isn't worth a bug in a contract that holds money.

A sensible workflow

  1. Write the clear version and get the tests passing first.
  2. Run the tests with npx hardhat test mocha --gas-stats and look at the most expensive functions and their callers.
  3. Start with storage: constants, immutables, packing, fewer writes.
  4. Change one thing at a time and re-measure under the production profile.
  5. Keep the tests green after every change, and note any change that trades safety for gas.

Before you put money behind any optimized contract, have it reviewed. Cleverness is where bugs live, and the audit preparation checklist is the next step.

Build with me

Want your contracts lean and safe?

I build and test Solidity with measurements, not guesswork. If you'd like a gas review of your own contracts, get in touch.

See services Get in touch

What I ran this against

  • Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. Each number below is gas used in one transaction, or a gas estimate for read-only functions, on the simulated network, measured once with the default profile (optimizer off) and once with the production profile (optimizer on, 200 runs).
  • These are single measurements on a toy contract. Real contracts differ, other compiler versions differ, and one change can interact with another. Treat the numbers as an illustration of relative size, and measure your own code with --gas-stats.

Sources checked

  • Solidity 0.8.22 release announcement (the compiler now removes the overflow check on simple for-loop counters, even when the rest of the optimizer is off): soliditylang.org.
  • Hardhat 3 command line: the --gas-stats and --build-profile options are listed by npx hardhat test --help in the version used.