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.
| Operation | Approximate gas cost | Practical implication |
|---|---|---|
| SSTORE zero to nonzero | 20,000 plus cold access | Avoid creating new storage entries |
| SSTORE nonzero to nonzero | About 2,900 when warm | Updating is cheaper than creating |
| SLOAD cold / warm | 2,100 / 100 | Cache repeated reads in memory |
| ADD, SUB, MUL | 3 to 5 | Arithmetic is nearly free |
| Calldata byte (nonzero / zero) | 16 / 4 | Compact inputs reduce cost |
| LOG with one topic | About 750 plus data | Events are cheaper than storage |
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.
| Technique | What it changes | Typical saving |
|---|---|---|
| Storage packing | Groups small variables into one 32-byte slot | Up to thousands of gas per write |
| Caching storage reads | Copies a slot into a local variable once | About 100 gas per avoided warm read |
| calldata parameters | Reads external arrays without copying to memory | Hundreds of gas for large inputs |
| immutable and constant | Embeds fixed values in bytecode | Removes an SLOAD per access |
| Custom errors | Replaces revert strings with 4-byte selectors | Smaller bytecode and cheaper reverts |
| Unchecked arithmetic | Skips overflow checks where proven safe | Tens of gas per operation |
| Events instead of storage | Stores history off-chain via logs | Large savings for archival data |
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 profile | Suggested runs value | Reason |
|---|---|---|
| Rarely called factory or one-off | 1 to 200 | Deployment cost dominates |
| Typical application contract | 200 (default) | Balanced compromise |
| High-volume token or exchange | 10,000 or more | Runtime savings repeat millions of times |
| Contract near the size limit | Low value plus refactoring | Bytecode must fit under 24,576 bytes |
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.
| Mistake | Consequence | Safer practice |
|---|---|---|
| Unchecked math without proof | Silent overflow or underflow | Use unchecked only with proven bounds |
| Unreviewed inline assembly | Memory corruption or wrong storage slot | Limit assembly and audit it separately |
| Unbounded loops over storage | Function exceeds the gas limit | Paginate or redesign data structures |
| Removed access checks | Unauthorized state changes | Never trade authorization for gas |
| Packing values into small types | Truncation of large values | Validate ranges before casting |
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.