SolidityIn

Advanced Technical & Performance (Gas Optimization)

November 6, 2026 · admin · Uncategorized


Advanced Technical & Performance Strategies for EVM Development

In the Ethereum Virtual Machine (EVM), gas is more than just a transaction fee; it is the fundamental constraint of the system. For high-throughput protocols and complex DeFi applications, gas optimization is the difference between a successful product and an unusable one. This article dives into advanced techniques that go beyond basic uint choices, exploring the deep mechanics of the EVM.

1. Storage Layout and Variable Packing

The most expensive operation in Solidity is SSTORE (writing to storage). Each storage slot is 32 bytes. By carefully ordering variables, you can “pack” multiple variables into a single slot.

The Packing Mechanic

Solidity stores variables in the order they are declared. If multiple variables fit into a single 32-byte word, they are packed together.


// Inefficient: Uses 3 slots
struct User {
uint256 id; // Slot 0
bool isActive; // Slot 1
uint256 balance; // Slot 2
}
// Efficient: Uses 2 slots
struct OptimizedUser {
uint256 id; // Slot 0
uint128 balance; // Slot 1 (half slot)
bool isActive; // Slot 1 (1 byte)
address wallet; // Slot 1 (20 bytes) - Total < 32 bytes
}

Pro Tip: Variable packing only applies to storage. In memory or stack, the EVM often pads values to 32 bytes anyway, so packing uint8 inside a function body may actually increase gas due to the extra masking operations.

2. Calldata vs. Memory

When passing large arrays or structs to external functions, using calldata is significantly cheaper than memory.

  • Memory: The EVM creates a copy of the data, which involves gas-heavy allocation.
  • Calldata: A non-modifiable, non-persistent area where function arguments are stored. It avoids the copy overhead.


// Expensive: Copies array to memory
function processData(uint256[] memory data) external { ... }
// Optimized: Reads directly from transaction input
function processData(uint256[] calldata data) external { ... }

3. The Power of “Unchecked” Arithmetic

Since Solidity 0.8.0, the compiler automatically checks for overflows and underflows. While safer, this adds extra opcodes. For counters in loops or logic where you are mathematically certain overflow is impossible, use unchecked.


// Optimized loop
for (uint256 i = 0; i < length; ) {
// Logic here
unchecked { ++i; }
}

Using ++i (prefix) is also slightly cheaper than i++ (postfix) because it doesn’t need to return the value before incrementing.

4. Bit Shifting vs. Exponentiation

In the EVM, mathematical operations have varying costs. Bitwise operations are significantly cheaper than arithmetic ones.

  • To multiply by a power of 2, use << (left shift).
  • To divide by a power of 2, use >> (right shift).


// Expensive
uint256 x = y * 8;
// Cheaper
uint256 x = y << 3;

5. Yul and Inline Assembly

For the ultimate performance, developers turn to Yul, Solidity’s intermediate language. It allows you to bypass some of the compiler’s safety overhead and interact directly with the stack.

Warning: Assembly skips safety checks like type checking and overflow protection. Only use it for highly audited, gas-critical sections.


function assemblyAdd(uint256 x, uint256 y) public pure returns (uint256 z) {
assembly {
z := add(x, y)
}
}

Assembly is particularly effective for mload and mstore operations when dealing with dynamic bytes or hashing, where Solidity’s default behavior adds unnecessary padding.

6. Short-Circuiting and Errors

Order your require() statements and logical operators logically. Put the check most likely to fail (or the cheapest check) first.


// Optimized: If isOwner is false, the expensive function call is skipped
require(isOwner || someExpensiveCheck(), "Not authorized");

Additionally, use Custom Errors (introduced in 0.8.4) instead of string revert messages. Strings are stored as data and cost gas; Custom Errors are selectors that save roughly 200-300 gas per revert.


error UnauthorizedUser(address user);
if (msg.sender != owner) revert UnauthorizedUser(msg.sender);

Conclusion

Gas optimization is a balancing act between readability, security, and cost. While variable packing and calldata should be standard practice, deep assembly and bit-shifting should be reserved for bottlenecks. Always use tools like hardhat-gas-reporter and the Foundry gas-report to benchmark your changes.

Tags: , , ,