SolidityIn

Squeezing the EVM: Advanced Gas Optimization Techniques in Solidity

November 6, 2026 · admin · Uncategorized


Advanced Gas Optimization Techniques in Solidity

In the Ethereum Virtual Machine (EVM), gas is more than just a transaction fee; it is the fundamental constraint of the ecosystem. For developers, writing functional code is the baseline, but writing gas-efficient code is the hallmark of a master. As protocols scale, a few thousand gas saved per transaction can translate into millions of dollars in saved value for users.

While basic tips like “use external instead of public” are common knowledge, this article dives into the advanced architectural patterns and low-level tricks used by top-tier DeFi protocols.

1. Bitmasking and Bitmaps

In Solidity, a bool takes up 8 bits, but due to how storage slots work, a single bool often ends up occupying a full 256-bit slot if not packed. When you need to track hundreds of “true/false” states (like whether an address has claimed an airdrop), using a mapping(uint256 => bool) is prohibitively expensive.

The Solution: Use a single uint256 as a bitmap. One uint256 can store 256 boolean flags.

// Instead of mapping(address => bool) public hasClaimed;
mapping(uint256 => uint256) public claimBitMap;
function isClaimed(uint256 index) public view returns (bool) {
uint256 wordIndex = index / 256;
uint256 bitIndex = index % 256;
uint256 word = claimBitMap[wordIndex];
uint256 mask = (1 << bitIndex);
return (word & mask) == mask;
}

2. Error String Optimization

Prior to Solidity 0.8.4, developers relied on require(condition, "Very long error message..."). These strings are stored in the contract’s bytecode, increasing deployment costs and execution gas when the revert triggers.

The Solution: Custom Errors. They are significantly cheaper because they are handled via four-byte selectors rather than long ASCII strings.

// Expensive
require(balance >= amount, "Insufficient balance for withdrawal");
// Cheap (Advanced)
error InsufficientBalance(uint256 available, uint256 required);
if (balance < amount) {
revert InsufficientBalance(balance, amount);
}

3. The “Unchecked” Loop Increment

Since Solidity 0.8.0, arithmetic operations come with built-in overflow/underflow checks. While safer, these checks add JUMP instructions to every iteration of a loop. For a loop index i, we know it will never overflow if it’s bounded by an array length.

The Solution: Wrap the increment in an unchecked block.

// Standard loop
for (uint256 i = 0; i < length; i++) { ... }
// Optimized loop
for (uint256 i = 0; i < length;) {
// ... logic ...
unchecked { i++; }
}

4. Cold vs. Warm Access (EIP-2929)

Since the Berlin hard fork, the EVM distinguishes between “cold” access (the first time a slot is touched) and “warm” access. Accessing a cold storage slot costs 2,100 gas, while warm access costs only 100.

The Optimization: Cache state variables in local memory if they are read more than once in a function. Reading a local memory variable is significantly cheaper than a SLOAD (storage read), even if that slot is already “warm.”

// Expensive: 2 SLOADs
uint256 total = globalCount + 1;
globalCount = total + 5;
// Efficient: 1 SLOAD, 1 SSTORE
uint256 _globalCount = globalCount;
_globalCount += 6;
globalCount = _globalCount;

5. Calldata vs. Memory for Read-Only Arguments

When passing large arrays or structs to a function, specifying the location as memory forces the EVM to copy the data from calldata to memory, which costs gas.

The Solution: Use calldata for external function arguments. This allows the EVM to read the data directly from the transaction input without the overhead of memory allocation.

// Higher gas
function processData(uint256[] memory data) external { ... }
// Lower gas
function processData(uint256[] calldata data) external { ... }

6. Assembly (Yul) for Surgical Precision

When you’ve exhausted Solidity’s syntax, you can drop into Yul (Solidity’s inline assembly). Assembly allows you to bypass the safety checks and abstractions of the high-level compiler.

Warning: Use assembly sparingly. It bypasses many compiler security features and makes code harder to audit.

Common uses include using mstore for custom memory layouts or using create2 for deterministic contract deployments with minimal boilerplate.

Conclusion

Advanced gas optimization is a game of trade-offs between readability, security, and efficiency. Techniques like Bitmasking and Custom Errors should be standard in any modern developer’s toolkit, while Assembly and Unchecked increments should be used where performance is mission-critical.

Remember: The cheapest code is the code that never runs. Always question whether a piece of data actually needs to be stored on-chain or if it can be handled via events or off-chain Merkle proofs.

© 2023 Solidity Optimization Guide. For educational purposes only.

Tags: , , ,