Glossary

Gas Optimization

Gas optimization reduces the computational cost of blockchain transactions through efficient code, batching, and data compression techniques.

Key Takeaways

  • Gas optimization reduces the cost of executing smart contracts and transactions by minimizing expensive operations like storage writes, which cost up to 20,000 gas per slot on Ethereum.
  • Common techniques include storage packing, calldata reduction, transaction batching, and using events instead of storage: together, these can cut gas consumption by 40% to 70%.
  • Layer 2 networks and blob transactions represent the most impactful gas optimization at scale, reducing transaction costs from dollars to fractions of a cent.

What Is Gas Optimization?

Gas optimization is the practice of reducing the computational resources required to execute blockchain transactions, particularly on the Ethereum Virtual Machine (EVM). Every operation on Ethereum costs a specific amount of gas, and users pay for that gas in the network's native currency. Gas optimization aims to accomplish the same result using fewer operations or cheaper alternatives.

The need for gas optimization arises from Ethereum's execution model: every node in the network must re-execute every transaction to validate it. The gas limit caps how much computation a single block can contain, making block space a scarce resource. When demand exceeds supply, the fee market drives up the gas price, and poorly optimized contracts become expensive to use. During peak congestion, a single token swap on Ethereum mainnet can cost tens of dollars or more.

How It Works

Gas optimization operates at multiple levels: the EVM opcode level, the Solidity compiler level, the contract architecture level, and the network level. Each layer offers different strategies for reducing costs.

Storage Optimization

Storage is the most expensive resource in the EVM. Writing a new value to a previously empty storage slot (SSTORE) costs 20,000 gas. Modifying an existing value costs 5,000 gas. By contrast, reading from storage (SLOAD) costs 2,100 gas on the first access and 100 gas on subsequent reads within the same transaction. These costs dwarf most other operations: a simple addition (ADD) costs just 3 gas.

Storage packing exploits the fact that the EVM operates on 32-byte slots. Multiple variables smaller than 32 bytes can share the same slot, reducing the number of storage reads and writes:

// Unoptimized: each variable occupies a full 32-byte slot
// 3 separate SSTORE operations = 60,000 gas
uint256 amount;     // slot 0 (32 bytes)
uint256 timestamp;  // slot 1 (32 bytes)
uint256 status;     // slot 2 (32 bytes)

// Optimized: pack into fewer slots
// 2 SSTORE operations = 40,000 gas
uint128 amount;     // slot 0 (16 bytes)
uint64 timestamp;   // slot 0 (8 bytes) — same slot
uint64 status;      // slot 0 (8 bytes) — same slot

This technique is especially effective for structs that are read or written frequently. A packed struct that fits in two slots instead of four saves thousands of gas on every access.

Calldata and Memory Efficiency

Data passed to a function can live in three locations: storage, memory, or calldata. Each has a different cost profile:

  • Storage: 2,100+ gas per read, 5,000+ gas per write
  • Memory: 3 gas per 32-byte word (plus quadratic expansion costs for large allocations)
  • Calldata: 16 gas per non-zero byte, 4 gas per zero byte (read-only)

For external functions that only read their arguments without modifying them, using calldata instead of memory avoids copying data into memory entirely, saving roughly 1,800+ gas for array parameters.

Code-Level Techniques

Several patterns reduce gas at the Solidity code level:

  • Custom errors instead of revert strings: error Unauthorized(); costs significantly less gas than require(authorized, "Not authorized"); because revert strings are stored in contract bytecode and cost gas to both deploy and execute
  • Events instead of storage: emitting an event costs roughly 375 base gas plus 375 per indexed parameter, compared to 20,000+ gas for a storage write. For data that only needs to be read off-chain, events are far cheaper
  • Constants and immutables: variables declared as constant or immutable are embedded directly in the contract bytecode, avoiding storage reads entirely
  • Unchecked arithmetic: for operations where overflow is impossible by design, wrapping code in unchecked {} skips Solidity's built-in overflow checks, saving gas on each arithmetic operation
  • Short-circuit evaluation: placing cheaper conditions first in logical expressions (using && or ||) avoids evaluating expensive conditions when the result is already determined
// Gas-optimized patterns
error InsufficientBalance(uint256 requested, uint256 available);

uint256 public constant FEE_BPS = 30;
uint256 public immutable deployTimestamp;

function processItems(uint256[] calldata items) external {
    uint256 len = items.length;
    for (uint256 i; i < len;) {
        // process items[i]
        unchecked { ++i; }
    }
}

Layer 2 Gas Savings

While code-level optimizations reduce gas within individual contracts, the most dramatic gas savings come from moving execution off Ethereum mainnet entirely. Rollups batch hundreds or thousands of transactions and post compressed data to Ethereum, amortizing the fixed costs across many users.

The introduction of blob transactions through EIP-4844 (the Dencun upgrade in March 2024) reduced Layer 2 fees by 10x to 100x. Instead of posting transaction data as expensive calldata, rollups now use a separate "blob" data market with its own base fee. This created a dedicated data availability layer that is far cheaper than competing for regular block space.

The impact was immediate: Base saw a 224% increase in transaction volume following the upgrade, and routine Layer 2 swaps dropped to fractions of a cent. Ethereum subsequently doubled blob capacity through the Pectra upgrade in May 2025, increasing per-block targets from 3 to 6 blobs, and further expanded capacity through Fusaka in December 2025 with per-block targets reaching 14 blobs.

Gas Costs Across Chains

The cost of a simple transaction varies dramatically depending on the network:

NetworkTypical Transaction CostArchitecture
Ethereum Mainnet$1 to $10+Layer 1
Arbitrum One< $0.01 to $0.30Optimistic Rollup
Optimism< $0.01 to $0.50Optimistic Rollup
Base< $0.01Optimistic Rollup
Bitcoin (on-chain)$0.50 to $5+Layer 1 (UTXO)
Spark / LightningNear zeroOff-chain

These figures fluctuate with network congestion. During gas wars or periods of high demand, Ethereum mainnet fees can spike well above $50 per transaction.

User-Facing Strategies

Not all gas optimization happens at the smart contract level. End users and application developers can reduce costs through several strategies:

  • Timing transactions during low-congestion periods: gas prices follow predictable patterns, typically dropping on weekends and during off-peak hours (early morning UTC). Gas tracking tools help users identify optimal windows
  • Transaction batching: combining multiple operations into a single transaction amortizes the base 21,000 gas cost across all operations
  • Fee abstraction services: protocols that sponsor gas fees on behalf of users, allowing interaction with dApps without holding the native token
  • Aggregation services: DEX aggregators and intent-based protocols find the most gas-efficient route for swaps and other operations
  • EIP-1559 fee estimation: setting an appropriate priority fee and max fee rather than overpaying ensures transactions confirm without wasting gas

Why It Matters

Gas optimization directly impacts the usability and economics of blockchain applications. For protocols processing millions of transactions, even small per-transaction savings compound into significant cost reductions. For end users, high gas costs can make small-value transactions uneconomical: a $2 fee on a $5 transfer destroys the value proposition entirely.

This cost pressure is a primary driver behind Layer 2 adoption and alternative architectures. Off-chain protocols like Spark and the Lightning Network bypass on-chain gas entirely for routine payments, settling only when participants open or close channels. This makes micropayments and high-frequency transactions practical in ways that are impossible on Layer 1 networks.

The evolution of gas optimization also reflects a broader trend in blockchain design: separating execution from data availability. As rollups move computation off-chain and use blobs for data posting, the definition of "gas optimization" expands from writing efficient opcodes to choosing the right layer for each operation. For a deeper look at how blob transactions reshaped Layer 2 economics, see EIP-4844 and Blob Fees.

Risks and Considerations

Over-Optimization and Readability

Aggressive gas optimization can produce code that is difficult to audit and maintain. Techniques like inline assembly, bit manipulation, and extreme variable packing sacrifice readability. For smart contracts handling significant value, security and correctness should take priority over marginal gas savings. A smart contract audit becomes more difficult when optimized code obscures intent.

Compiler Improvements

Some manual optimizations become unnecessary as the Solidity compiler improves. Patterns that saved gas in earlier compiler versions may have no effect or even increase costs in newer versions. Developers should profile gas usage with tools like Foundry's gas reports or Hardhat Gas Reporter rather than applying optimization patterns blindly.

Cross-Chain Differences

Gas optimization techniques that work on Ethereum mainnet may not apply to Layer 2 networks. On rollups, the dominant cost is often calldata (data posted to Layer 1), not execution. Optimizing for fewer storage writes has diminishing returns when the bottleneck is transaction data size. Each chain's fee model requires its own optimization strategy.

Security Trade-Offs

Certain optimizations introduce risk. Using unchecked arithmetic removes overflow protection, creating potential vulnerabilities if the developer's assumptions are wrong. Minimizing storage to save gas can eliminate data needed for reentrancy guards or access control checks. The cheapest transaction is one that loses no funds.

This glossary entry is for informational purposes only and does not constitute financial or investment advice. Always do your own research before using any protocol or technology.