Solidity gas optimization: 16 patterns we use on audits
Sixteen gas patterns, ranked by real-world impact on the contracts we audited in 2025.
Sixteen gas patterns, ranked by real-world impact on the contracts we audited in 2025.
We audited 11 Solidity codebases in 2025. Every single one had 15-40% avoidable gas cost, mostly in the same patterns. Here they are in order of impact.
A `uint256` and a `bool` in separate slots cost 20k gas per write. Pack them into one slot (`uint128 + bool + address`) and the second write is a few hundred gas. Look for structs with mixed-size fields.
`require(x, "NotOwner")` deploys the string to bytecode. `error NotOwner(); revert NotOwner();` is ~50 bytes smaller and costs less at runtime.
// before
require(msg.sender == owner, "NotOwner");
// after
error NotOwner();
if (msg.sender != owner) revert NotOwner();External function arrays/structs: use `calldata` unless you mutate. Saves the copy + a chunk of stack.
Solidity 0.8+ checks every math op. Where you've already proven no overflow (post-condition from a prior `require`, or a bounded loop counter), wrap in `unchecked { ... }` for significant gas savings.
`immutable` is cheaper to read than `constant` when the value is computed at construction (like `owner = msg.sender`). `constant` wins only for literals.
`for (uint i; i < n; ++i)` beats `i++` (pre-increment saves a few gas per iter). Cache `n` if it's a storage read. If the work can stop early, `break` · don't run the full loop.
Every `SSTORE` is ~20k gas. An `emit` is ~1.5k. If data doesn't need on-chain reads - historical logs, UI feeds, analytics - use events, not storage.
Run forge snapshot before and after each change. Measure, don't guess · a 'clever' optimization can cost gas via bytecode bloat.
Don't optimize gas before you've got correctness + audit. A gas-optimized contract that reverts under edge conditions is a catastrophe, not a win. Correctness first, then gas · in that order.

Founder, DField Solutions
I'm a full-stack engineer and I build across the whole stack myself · AI agents, web and mobile apps, blockchain, backends, security, right down to the OS layer. If it's software, I've probably built it and broken it.
Let's talk about your project. 30 minutes, no strings.