Gas Optimization

Production engineering guide for gas optimization in Web3 and blockchain systems.

Gas Optimization is the practice of reducing the cost of executing transactions on a blockchain, particularly Ethereum and EVM-compatible chains. It matters when every transaction incurs a fee proportional to the computational work it demands—measured in gas—and when that cost directly impacts user experience, protocol economics, and developer efficiency. Gas optimization is essential for dApps, smart contracts, and on-chain infrastructure where transaction volume and frequency are high.

Core Techniques

Minimize Storage Reads and Writes

Each SLOAD (storage read) costs 200 gas; each SSTORE (storage write) costs 20,000 gas for a fresh slot, and 5,000 for an updated slot. Reducing the number of storage operations is a primary lever for cost reduction.

To minimize storage access:

struct User {
    uint256 balance;
    uint256 lastActive;
    bool isActive;
    bytes32 metadata;
}

// Efficient: fits into 2 slots (32 bytes each)
struct UserCompact {
    uint256 balance;
    uint256 lastActive;
    bool isActive;
    bytes32 metadata;
}

Use memory arrays for intermediate data in functions:

function processUsers(User[] memory users) public {
    for (uint i = 0; i < users.length; i++) {
        User storage user = users[i]; // reference to storage
        user.balance += 100;
        user.lastActive = block.timestamp;
    }
}

Optimize Function Call Costs

Function calls have overhead: CALL, CALLCODE, DELEGATECALL, STATICCALL. Choose the right call type based on data access and side effect needs.

contract Token {
    mapping(address => uint256) public balances;

    function transfer(address to, uint256 amount) external {
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }

    function balanceOf(address owner) external view returns (uint256) {
        return balances[owner];
    }

    function totalSupply() external pure returns (uint256) {
        return 1_000_000 ether;
    }
}

Reduce ABI Overhead in Transactions

ABI (Application Binary Interface) encoding adds gas cost. For a transfer call:

To reduce ABI size:

function mint(address to, uint256 amount, bytes memory metadata) external {
    // Calldata: 32 (to) + 32 (amount) + 32 (metadata.length) + 32 (metadata) = 130 bytes
    // Packed: use bytes32 for metadata if ≤ 32 bytes
}

Use Solidity’s immutable and constant Properly

Use immutable for values that never change post-deployment:

contract Pool {
    address public immutable owner;
    uint256 public immutable feeRate;
    uint256 public constant MAX_DEPOSIT = 100_000 ether;

    constructor(address _owner, uint256 _feeRate) {
        owner = _owner;
        feeRate = _feeRate;
    }
}

immutable variables are loaded once from contract code during CREATE, reducing gas in every call.

Efficient Use of memory and storage Pointers

Avoid unnecessary SLOAD and SSTORE by using memory pointers to reduce access cost.

function updateBalances(address[] memory accounts, uint256[] memory amounts) external {
    for (uint i = 0; i < accounts.length; i++) {
        address account = accounts[i];
        uint256 amount = amounts[i];
        // Use storage pointer to avoid repeated SLOAD
        Storage storage accountData = accountDataMap[account];
        accountData.balance += amount;
        accountData.lastUpdated = block.timestamp;
    }
}

Optimize Loop Constructs

Loops in Solidity are expensive due to:

Use for loops with memory arrays, and precompute loop bounds.

function batchTransfer(address[] memory receivers, uint256[] memory amounts) external {
    require(receivers.length == amounts.length, "Length mismatch");
    uint256 len = receivers.length;

    for (uint i = 0; i < len; i++) {
        address receiver = receivers[i];
        uint256 amount = amounts[i];
        // Single SLOAD for receiver and amount
        balances[receiver] += amount;
    }
}

Optimize State Access with mapping Design

Use mapping keys that are small and predictable:

mapping(bytes32 => uint256) public userScores;

// Access: userScores[keccak256("alice")] = 95;
// Gas: 200 for SLOAD, 32 for calldata, 32 for key, 200 for SSTORE

Use mapping with struct to avoid repeated SLOAD:

mapping(address => User) public users;

function getUser(address user) external view returns (User memory) {
    return users[user]; // one SLOAD
}

Reduce Contract Deployment Costs

Deployment costs are dominated by:

To reduce deployment cost:

contract DAO {
    address public owner;
    uint256 public quorum;
    mapping(address => bool) public members;

    constructor(address _owner, uint256 _quorum) {
        owner = _owner;
        quorum = _quorum;
        members[_owner] = true;
    }

    function addMember(address member) external {
        members[member] = true;
    }
}

Use library Functions for Reusable Logic

library functions are deployed once and called via DELEGATECALL, reducing gas.

library Math {
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        return a + b;
    }
}

contract Calculator {
    function sum(uint256[] memory nums) public view returns (uint256) {
        uint256 total = 0;
        for (uint i = 0; i < nums.length; i++) {
            total = Math.add(total, nums[i]);
        }
        return total;
    }
}

Advanced Patterns

Batch Transactions

Batching multiple operations into a single transaction reduces gas per operation.

function batchDeposit(address[] memory accounts, uint256[] memory amounts) external {
    uint256 len = accounts.length;
    for (uint i = 0; i < len; i++) {
        balances[accounts[i]] += amounts[i];
    }
}

Each SSTORE is cheaper when batched, and the CALL overhead is amortized.

Use CREATE2 for Predictable Deployment

CREATE2 allows deterministic contract creation from a salt and initcode.

address contractAddr = address(
    keccak256(abi.encodePacked(
        byte(0xff),
        address(this),
        salt,
        keccak256(initcode)
    ))
);

Use CREATE2 to pre-deploy factory contracts or to enable stateless contracts.

Optimize event Emission

Events are indexed and stored in logs. Each LOG costs gas:

Index frequently queried fields:

event Transfer(address indexed from, address indexed to, uint256 amount, bytes32 metadata);

function transfer(address to, uint256 amount, bytes32 metadata) external {
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount, metadata);
}

Reduce calldata Size with packed ABI

Use packed ABI to minimize calldata size:

function mint(address to, uint256 amount, bytes32 metadata) external {
    // Packed: 32 + 32 + 32 + 32 = 128 bytes
    // Without packing: 32 + 32 + 32 + 32 + 32 + 32 = 192 bytes
}

Common Failure Modes

Overuse of SSTORE in Loops

Writing to storage in a loop without caching leads to high gas:

for (uint i = 0; i < 100; i++) {
    balances[addresses[i]] += 100; // 100 SSTOREs, each 20,000 gas
}

Each SSTORE costs 20,000 gas for new slots. If the loop is run frequently, this quickly becomes the dominant cost.

Misuse of memory and storage Variables

Confusing memory and storage leads to unnecessary SLOAD and SSTORE:

function updateBalance(address user, uint256 amount) external {
    balances[user] += amount; // SLOAD + SSTORE
    // But: balances[user] is storage, so reading it requires SLOAD
}

To fix: cache storage variables in memory:

function updateBalance(address user, uint256 amount) external {
    uint256 balance = balances[user]; // SLOAD
    balance += amount;
    balances[user] = balance; // SSTORE
}

Underuse of immutable and constant

Using uint256 for values that never change leads to unnecessary SSTORE and SLOAD:

contract Token {
    uint256 public totalSupply;
    uint256 public decimals = 18; // SSTORE in constructor, SLOAD on every call
}

Replace with immutable:

uint256 public immutable decimals;
constructor() {
    decimals = 18;
}

Now decimals is read from code, not storage.

Overuse of external Functions

Every external function call incurs:

Use internal or private for frequently called functions:

function _transfer(address from, address to, uint256 amount) internal {
    balances[from] -= amount;
    balances[to] += amount;
}

Ignoring CREATE vs CREATE2 Overhead

CREATE costs 32,000 gas, CREATE2 costs 32,000 + 100 * salt size.

Use CREATE2 when:

Misunderstanding SLOAD vs SSTORE Gas

SLOAD is 200 gas; SSTORE is 20,000 for new slots, 5,000 for updates.

Common mistake: writing to storage without considering update cost:

function updateSettings(string memory name, uint256 value) external {
    settings[name] = value; // SSTORE: 20,000 gas
}

But settings[name] is a mapping, so name is bytes32 key. If name is string, keccak256 is needed.

Tooling and Workflow

Build with solc and --optimize

solc --optimize --optimize-times 10 --evmVersion istanbul \
     --output-dir ./build \
     --combined-json abi,bin,storageLayout \
     contracts/*.sol

Use --optimize-times 10 for high optimization; --evmVersion istanbul for EIP-1884 (increased SLOAD gas).

Deploy with hardhat or foundry

// hardhat.config.js
module.exports = {
  solidity: {
    compilers: [
      {
        version: "0.8.20",
        settings: {
          optimizer: {
            enabled: true,
            runs: 100,
          },
        },
      },
    ],
  },
};

Analyze Gas Usage with hardhat-gas-reporter

npx hardhat test --network mainnet

Reports gas usage per test, per transaction, and per contract.

Debug with console.log in Solidity

Use emit and console.log for detailed gas tracing:

event Debug(string message, uint256 value);

function withdraw(uint256 amount) external {
    emit Debug("Withdrawing", amount);
    balances[msg.sender] -= amount;
    emit Debug("Balance updated", balances[msg.sender]);
}

Use console.log from hardhat or foundry to capture logs.

Monitor Gas in Production

Use ethers.js or web3.js to monitor gas usage:

const gasPrice = await provider.getGasPrice();
const gasLimit = await contract.estimateGas("transfer", [to, amount]);
const cost = gasPrice * gasLimit;
console.log("Transaction cost:", cost.toString());

Use eth_getTransactionReceipt to inspect actual gas used and gas price.

This page was rewritten on 18 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.