🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Gas Optimization Techniques for Smart Contracts

Advanced Solidity DevelopmentđŸŸĸ Free Lesson

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

Storage Slot PackingBefore (4 slots)amount (16 bytes)fee (16 bytes)owner (20 bytes)bool (1 byte)4 SSTORE operations × 20,000 gas = 80,000 gasAfter (2 slots)amount (16 bytes)fee (16 bytes)owner (20 bytes)bool (1 byte)2 SSTORE operations × 20,000 gas = 40,000 gas (50% savings)

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 TypeMemory CostCalldata CostSavings
uint256[]20,000 + 3 × length4 × length~80%
bytes20,000 + 3 × length4 × length~80%
string20,000 + 3 × length4 × length~80%
struct20,000 + struct sizestruct size~95%
mappingNot supportedNot supportedN/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:

OperationRefundMaximum Refund
Storage Reset4,800 gas20% of gas used
SELFDESTRUCT24,000 gas20% of gas used
Log Emission375 gas20% of gas used
Bloom Filter10 gas20% of gas used

Refund Calculation Formula

EIP-4844: Blob Transactions

EIP-4844 introduced "blob-carrying transactions" for cheaper data availability.

Blob vs Calldata Comparison

Blob vs Calldata CostsCalldata: 16 gas per byteBlob: ~1 gas per byte (after EIP-4844)Cost Reduction: ~93%Blob Size: 128 KB per blobMax Blobs per Block: 6 (EIP-4844)

L2 Gas Models

Different L2 solutions have varying gas pricing mechanisms:

L2 SolutionGas ModelData AvailabilityCost per Byte
OptimismBedrockOn-chain (EIP-4844)~1 gas
ArbitrumNitroOn-chain (EIP-4844)~1 gas
zkSync ErazkEVMOn-chain (EIP-4844)~1 gas
StarkNetSTARKOn-chain (EIP-4844)~1 gas
Polygon zkEVMzkEVMOn-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

TechniqueGas SavingsComplexityReadabilityRecommended
Storage PackingHighMediumMediumYes
CalldataHighLowHighYes
Unchecked BlocksMediumLowMediumConditional
AssemblyVery HighHighLowExpert Only
Custom ErrorsLowLowHighYes

Interview Questions

  1. What are the key differences between memory and calldata in terms of gas costs, and when would you choose one over the other?

  2. Explain how EIP-4844 reduces gas costs for L2 rollups. What are the limitations of blob transactions?

  3. 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

  1. What is the maximum gas refund percentage for storage operations?

    • A) 50%
    • B) 20%
    • C) 10%
    • D) 5%
  2. 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
  3. 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Blockchain Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement