Gas optimization

On this page 7

Gas optimization is the discipline of designing and writing smart contracts so that deploying them and calling their functions consumes as little gas as possible, without changing what the code does or weakening its security. In Crypto & blockchain engineering, every operation executed by the Ethereum Virtual Machine (EVM) has a fixed gas cost, and users pay for that gas in the network’s native currency, so inefficient code translates directly into higher fees for every person who interacts with a contract.

The practice matters most for contracts that are called thousands or millions of times, such as tokens, decentralized exchanges and lending protocols. A saving of a few thousand gas per call can add up to substantial aggregate savings for users, while careless optimization can introduce subtle bugs that a later smart contract audit must catch.

How gas costs arise in the EVM

Gas costs arise because the EVM assigns a fixed price to every opcode, reflecting how much computation, memory and permanent storage the operation forces every node to handle. The total gas used by a transaction is the intrinsic cost (21,000 gas for a simple transfer, plus a charge for calldata bytes) added to the cost of every opcode executed. The user then pays gas used multiplied by the gas price, which under EIP-1559 consists of a burned base fee and an optional priority tip.

The single largest cost driver is persistent storage. Writing a new nonzero value to a storage slot costs about 20,000 gas, while ordinary arithmetic costs only 3 to 5 gas. Since the Berlin upgrade (EIP-2929), the first access to a storage slot or external address within a transaction is a cold access and costs considerably more than later warm accesses. The table below shows typical costs that shape most optimization decisions.

OperationApproximate gas costPractical implication
SSTORE zero to nonzero20,000 plus cold accessAvoid creating new storage entries
SSTORE nonzero to nonzeroAbout 2,900 when warmUpdating is cheaper than creating
SLOAD cold / warm2,100 / 100Cache repeated reads in memory
ADD, SUB, MUL3 to 5Arithmetic is nearly free
Calldata byte (nonzero / zero)16 / 4Compact inputs reduce cost
LOG with one topicAbout 750 plus dataEvents are cheaper than storage
Representative EVM operation costs after recent network upgrades

Exact figures change with network upgrades, so experienced developers measure gas with tooling rather than memorizing numbers. Refunds for clearing storage were also reduced by EIP-3529, which ended the gas token pattern that once exploited those refunds.

Core gas optimization techniques

Most gas optimization techniques reduce the number of storage operations, shrink the data a transaction carries or remove redundant computation. In Solidity, the most effective changes are structural rather than cosmetic, because storage layout and data flow dominate the bill far more than individual arithmetic statements.

TechniqueWhat it changesTypical saving
Storage packingGroups small variables into one 32-byte slotUp to thousands of gas per write
Caching storage readsCopies a slot into a local variable onceAbout 100 gas per avoided warm read
calldata parametersReads external arrays without copying to memoryHundreds of gas for large inputs
immutable and constantEmbeds fixed values in bytecodeRemoves an SLOAD per access
Custom errorsReplaces revert strings with 4-byte selectorsSmaller bytecode and cheaper reverts
Unchecked arithmeticSkips overflow checks where proven safeTens of gas per operation
Events instead of storageStores history off-chain via logsLarge savings for archival data
Common techniques and their typical effect

Other techniques include short-circuiting conditions so the cheapest check runs first, using mappings instead of arrays when iteration is not needed, and batching several actions into one transaction so the 21,000 gas base cost is paid only once. Merkle proofs let a contract verify membership in a large list, such as an airdrop allowlist, by storing a single 32-byte root instead of thousands of addresses.

At the advanced end, developers write inline assembly (Yul) to control memory and storage directly, or deploy minimal proxy clones (EIP-1167) that reuse one implementation’s bytecode. These methods deliver real savings but bypass compiler safety checks, so they demand careful review.

Deployment cost versus runtime cost

Gas optimization always balances deployment cost, paid once when the contract is created, against runtime cost, paid on every call. Deployment charges about 200 gas per byte of stored bytecode, and EIP-170 caps contract size at 24,576 bytes, so large contracts face both a cost and a hard limit.

The Solidity compiler exposes this trade-off through the optimizer runs parameter. A low value tells the optimizer to favor small bytecode, while a high value favors cheaper execution at the price of larger code. The following table summarizes how to choose.

Contract profileSuggested runs valueReason
Rarely called factory or one-off1 to 200Deployment cost dominates
Typical application contract200 (default)Balanced compromise
High-volume token or exchange10,000 or moreRuntime savings repeat millions of times
Contract near the size limitLow value plus refactoringBytecode must fit under 24,576 bytes
Choosing the optimizer runs setting

The via-IR compilation pipeline, which routes Solidity through the Yul intermediate representation, can produce more efficient code for complex contracts, although it increases compile times and occasionally changes gas profiles unexpectedly, so results should be measured rather than assumed.

Measuring and verifying gas usage

Reliable gas optimization depends on measurement before and after every change. Development frameworks such as Foundry and Hardhat produce gas reports that list the minimum, average and maximum cost of each function across a test suite, and Foundry’s gas snapshots let a team detect regressions in continuous integration.

  • Benchmark realistic paths, including cold storage access and first-time users, not only warm repeated calls.
  • Compare against a baseline commit so that each optimization shows a measurable gain.
  • Keep the full test suite green, because a cheaper function that behaves differently is a defect.
  • Inspect the bytecode or opcode trace when a change saves less than expected.

Measurement also exposes false optimizations. Micro-tweaks that were valuable under older compiler versions, such as manually replacing loop counters, are often already handled by the optimizer, and keeping them only reduces readability.

Risks and common mistakes

The principal risk of gas optimization is that cheaper code can be less safe code. Removing checks, using assembly or compressing data into packed fields all increase the chance of logical errors, and in smart contracts such errors are usually irreversible once deployed. The table below lists frequent mistakes.

MistakeConsequenceSafer practice
Unchecked math without proofSilent overflow or underflowUse unchecked only with proven bounds
Unreviewed inline assemblyMemory corruption or wrong storage slotLimit assembly and audit it separately
Unbounded loops over storageFunction exceeds the gas limitPaginate or redesign data structures
Removed access checksUnauthorized state changesNever trade authorization for gas
Packing values into small typesTruncation of large valuesValidate ranges before casting
Frequent optimization mistakes and their consequences

A further mistake is optimizing before the design is stable. Readable code is easier to audit, and audit findings in heavily optimized code are both more frequent and more expensive to fix. Many teams therefore optimize only measured hot paths and accept slightly higher costs elsewhere for the sake of clarity.

Gas optimization also differs from reducing the gas fee a user pays. Gas fees depend on network demand, and moving activity to a layer 2 rollup often cuts costs far more than any code change, although efficient code still lowers the bill there as well.

Stripped to the essentials

Every action a smart contract takes on a blockchain costs a small fee, measured in units called gas. Saving data permanently is the most expensive action, while simple math is very cheap. Gas optimization means writing contract code that does the same job with fewer costly steps.

Think of it like packing a moving truck. If you pack carefully, everything fits in one trip instead of three, and you pay less for the same move. The key point is that the savings must never come at the expense of safety, because a contract with a hidden mistake can lose real money.

Where it is applied

A small team maintains a token contract that users call about 50,000 times per day. A gas report shows that each transfer reads the same balance settings from storage three times and writes two separate small variables that sit in different storage slots.

The developers cache the repeated reads in local variables, pack the two small variables into one slot and replace long revert strings with custom errors. After measuring with their test suite, the average transfer drops from roughly 52,000 gas to about 44,000 gas, a saving of about 15 percent.

With a base fee of 20 gwei, that saving amounts to about 8 ETH less paid by users each day across the whole user base. Because the team changed only measured hot paths and kept every test passing, the follow-up audit found no new issues in the optimized code.