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.
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 packing to fit multiple fields into a single storage slot.storage variables in memory before processing.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;
}
}
Function calls have overhead: CALL, CALLCODE, DELEGATECALL, STATICCALL. Choose the right call type based on data access and side effect needs.
view functions for read-only operations: they do not consume gas for state changes.pure functions for computations without storage or memory access.external functions for public, high-frequency calls; use internal for intra-contract calls.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;
}
}
ABI (Application Binary Interface) encoding adds gas cost. For a transfer call:
msg.value costs 2300 gas for the call.calldata encoding cost is 16 gas per byte.To reduce ABI size:
packed structs to minimize calldata size.uint256 over uint128, uint64, and uint32 when possible.bytes over string for short, fixed-length data.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
}
immutable and constant Properlyimmutable variables are set at deployment and stored in contract code.constant variables are stored in storage and accessed via SLOAD.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.
memory and storage PointersAvoid 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;
}
}
Loops in Solidity are expensive due to:
for loops require SLOAD for loop variables.while loops require SLOAD and SSTORE per iteration.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;
}
}
mapping DesignUse mapping keys that are small and predictable:
bytes32 over address for keys when data fits.mapping for sparse data.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
}
Deployment costs are dominated by:
CREATE instruction (32,000 gas).SSTORE for constructor values.CALL for initial function calls.To reduce deployment cost:
constructor logic.immutable values to avoid SSTORE.setup function.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;
}
}
library Functions for Reusable Logiclibrary 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;
}
}
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.
CREATE2 for Predictable DeploymentCREATE2 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.
event EmissionEvents are indexed and stored in logs. Each LOG costs gas:
LOG0: 375 gasLOG1: 400 + 375LOG2: 425 + 375LOG3: 450 + 375LOG4: 475 + 375Index 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);
}
calldata Size with packed ABIUse packed ABI to minimize calldata size:
packed structs are encoded in a single bytes array.packed arrays use less space.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
}
SSTORE in LoopsWriting 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.
memory and storage VariablesConfusing 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
}
immutable and constantUsing 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.
external FunctionsEvery external function call incurs:
CALL cost: 2300 gas.calldata copy: 16 gas per byte.Use internal or private for frequently called functions:
function _transfer(address from, address to, uint256 amount) internal {
balances[from] -= amount;
balances[to] += amount;
}
CREATE vs CREATE2 OverheadCREATE costs 32,000 gas, CREATE2 costs 32,000 + 100 * salt size.
Use CREATE2 when:
SLOAD vs SSTORE GasSLOAD 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.
solc and --optimizesolc --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).
hardhat or foundry// hardhat.config.js
module.exports = {
solidity: {
compilers: [
{
version: "0.8.20",
settings: {
optimizer: {
enabled: true,
runs: 100,
},
},
},
],
},
};
hardhat-gas-reporternpx hardhat test --network mainnet
Reports gas usage per test, per transaction, and per contract.
console.log in SolidityUse 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.
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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy