Gas Optimization Techniques
Gas optimization is critical for reducing deployment costs and improving user experience on Ethereum and EVM-compatible chains.
Storage Packing
Solidity stores variables in 32-byte (256-bit) slots. Packing multiple variables into a single slot can dramatically reduce gas costs.
Before Optimization
contract Unpacked {
uint128 amount; // Slot 0 (16 bytes used)
uint128 fee; // Slot 1 (16 bytes used)
address owner; // Slot 2 (20 bytes used)
bool isActive; // Slot 3 (1 byte used)
}
After Optimization
contract Packed {
uint128 amount; // Slot 0: 16 bytes
uint128 fee; // Slot 0: 16 bytes (packed with amount)
address owner; // Slot 1: 20 bytes
bool isActive; // Slot 1: 1 byte (packed with owner)
}
Gas Savings Visualization
Calldata Optimization
Using calldata instead of memory for read-only function parameters saves gas by avoiding memory expansion.
// Expensive: Memory copy
function processMemory(uint256[] memory data) external pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;
}
// Optimized: Calldata reference
function processCalldata(uint256[] calldata data) external pure returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
sum += data[i];
}
return sum;
}
Gas Comparison Table
| Parameter Type | Memory Cost | Calldata Cost | Savings |
|---|---|---|---|
uint256[] | 20,000 + 3 Ã length | 4 Ã length | ~80% |
bytes | 20,000 + 3 Ã length | 4 Ã length | ~80% |
string | 20,000 + 3 Ã length | 4 Ã length | ~80% |
struct | 20,000 + struct size | struct size | ~95% |
mapping | Not supported | Not supported | N/A |
Loop Optimization
Pre-increment vs Post-increment
// Gas inefficient
for (uint256 i = 0; i < items.length; i++) {
process(items[i]);
}
// Optimized
for (uint256 i = 0; i < items.length; ++i) {
process(items[i]);
}
Caching Array Length
// Gas inefficient
for (uint256 i = 0; i < items.length; i++) {
process(items[i]);
}
// Optimized
uint256 len = items.length;
for (uint256 i = 0; i < len; ++i) {
process(items[i]);
}
Assembly Tricks
Unchecked Arithmetic
// Safe but expensive
function sumSafe(uint256[] calldata arr) external pure returns (uint256 total) {
for (uint256 i = 0; i < arr.length; ++i) {
total += arr[i];
}
}
// Optimized with unchecked
function sumOptimized(uint256[] calldata arr) external pure returns (uint256 total) {
for (uint256 i = 0; i < arr.length; ) {
total += arr[i];
unchecked { ++i; }
}
}
Custom Error Messages
// Expensive string error
error InsufficientBalance(uint256 available, uint256 required);
function withdraw(uint256 amount) external {
if (balances[msg.sender] < amount) {
revert InsufficientBalance(balances[msg.sender], amount);
}
balances[msg.sender] -= amount;
payable(msg.sender).transfer(amount);
}
Gas Refunds
Ethereum provides gas refunds for specific operations:
| Operation | Refund | Maximum Refund |
|---|---|---|
| Storage Reset | 4,800 gas | 20% of gas used |
| SELFDESTRUCT | 24,000 gas | 20% of gas used |
| Log Emission | 375 gas | 20% of gas used |
| Bloom Filter | 10 gas | 20% of gas used |
Refund Calculation Formula
EIP-4844: Blob Transactions
EIP-4844 introduced "blob-carrying transactions" for cheaper data availability.
Blob vs Calldata Comparison
L2 Gas Models
Different L2 solutions have varying gas pricing mechanisms:
| L2 Solution | Gas Model | Data Availability | Cost per Byte |
|---|---|---|---|
| Optimism | Bedrock | On-chain (EIP-4844) | ~1 gas |
| Arbitrum | Nitro | On-chain (EIP-4844) | ~1 gas |
| zkSync Era | zkEVM | On-chain (EIP-4844) | ~1 gas |
| StarkNet | STARK | On-chain (EIP-4844) | ~1 gas |
| Polygon zkEVM | zkEVM | On-chain (EIP-4844) | ~1 gas |
L2 Gas Cost Formula
Where L1 Data Cost follows:
Real-World Example: Uniswap V3 Router
Uniswap V3 implements several gas optimization patterns:
// 1. Using calldata for parameters
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
CalldataPath calldata path, // Calldata, not memory
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
// 2. Custom errors instead of require strings
error V2InvalidPath();
error V2InvalidAmountOut();
// 3. Assembly for efficient storage access
assembly {
let slot := add(paths.slot, path.hash)
let value := sload(slot)
}
Trade-offs
| Technique | Gas Savings | Complexity | Readability | Recommended |
|---|---|---|---|---|
| Storage Packing | High | Medium | Medium | Yes |
| Calldata | High | Low | High | Yes |
| Unchecked Blocks | Medium | Low | Medium | Conditional |
| Assembly | Very High | High | Low | Expert Only |
| Custom Errors | Low | Low | High | Yes |
Interview Questions
-
What are the key differences between
memoryandcalldatain terms of gas costs, and when would you choose one over the other? -
Explain how EIP-4844 reduces gas costs for L2 rollups. What are the limitations of blob transactions?
-
Design a gas-optimized storage pattern for a smart contract that needs to store 1000 user records with address, balance, and timestamp fields.
Quiz Questions
-
What is the maximum gas refund percentage for storage operations?
- A) 50%
- B) 20%
- C) 10%
- D) 5%
-
Which of the following is NOT a valid gas optimization technique?
- A) Using calldata instead of memory
- B) Packing multiple variables into one storage slot
- C) Using require() with string messages
- D) Using unchecked blocks for safe arithmetic
-
How many blobs can be included in a single Ethereum block after EIP-4844?
- A) 3
- B) 6
- C) 9
- D) 12
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions