0Pricing
Web3 & DApp Development Fundamentals · บทเรียน

เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส

เรียนรู้กลยุทธ์การเขียนโค้ด Solidity ให้ใช้แก๊สอย่างมีประสิทธิภาพ เพื่อลดต้นทุนธุรกรรมและเพิ่มประสิทธิภาพของ DApp บนบล็อกเชน

เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส เป็นบทเรียน Web3 & DApp Development Fundamentals ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Web3 & DApp Development Fundamentals และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Gas Optimization Matters

Welcome to the final lesson in DApp Security & Auditing! Today, we'll master Gas Optimization Techniques.

Gas is the fee paid to execute transactions on the Ethereum network. It's like fuel for your car.

  • Cost Reduction: Lower gas fees mean cheaper transactions for users.
  • Performance: Optimized contracts execute faster.
  • User Experience: Better performance leads to happier users and smoother DApps.

Understanding Gas Costs

Every operation the Ethereum Virtual Machine (EVM) performs costs a certain amount of gas. Complex operations cost more.

When you deploy or interact with a smart contract, you pay gas for:

  • Storing data on the blockchain (most expensive).
  • Performing computations.
  • Sending Ether.

Our goal is to write code that uses fewer of these expensive operations.

Storage vs. Memory vs. Calldata

Understanding where your data lives is key to saving gas. Each location has different costs:

  • Storage: Permanent, on-chain. Most expensive to read/write (SSTORE/SLOAD).
  • Memory: Temporary, exists only during function execution. Cheaper than storage.
  • Calldata: Immutable, read-only, temporary. Used for external function arguments. Cheapest for external inputs.

Prioritize using calldata or memory for variables that don't need to persist on-chain.

Minimize Storage Writes (SSTORE)

Writing to storage (SSTORE) is the single most expensive operation in Solidity. Always ask: does this variable really need to be stored on-chain?

Instead of updating a counter in storage for every iteration, compute it once at the end or use events to log changes.

Consider this simple example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract StorageCostExample {
    uint256 public counter;

    // High gas cost: writes to storage every call
    function incrementBad() public {
        counter++;
    }

    // Lower gas cost: only reads state
    function getCounter() public view returns (uint256) {
        return counter;
    }
}

Packing Storage Variables

Solidity stores variables in 256-bit (32-byte) 'slots'. If you declare multiple variables that fit within a single slot, they can be 'packed' together, saving gas.

For example, three uint8 variables take up less storage than three uint256 variables if declared consecutively. This saves SSTORE operations.

  • Declare smaller data types (e.g., uint8, bool) when possible.
  • Group variables of similar sizes together.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract StoragePacking {
    // These will likely pack into one slot
    uint8 public value1;
    bool public isActive;
    uint8 public value2;

    // This will take a separate slot
    address public owner;

    function setValues(uint8 _v1, bool _active, uint8 _v2) public {
        value1 = _v1;
        isActive = _active;
        value2 = _v2;
    }
}

Short-Circuiting Conditionals

When using logical operators like && (AND) or || (OR), Solidity uses 'short-circuiting'. This means it stops evaluating conditions once the result is known.

You can save gas by placing the cheaper, more likely-to-fail, or more likely-to-be-true conditions first.

  • For &&, put the condition most likely to be false first.
  • For ||, put the condition most likely to be true first.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ShortCircuitExample {
    uint256 public data = 100;

    function checkCondition(uint256 _input) public view returns (bool) {
        // Cheaper check (input) before more expensive check (storage read)
        return (_input > 0 && data > 50); 
    }
}

Efficient Loops & Iterations

Loops can be gas-expensive, especially if they iterate over large arrays stored in storage. Avoid unbounded loops or loops over dynamic arrays in storage when possible.

  • Process data off-chain if possible.
  • Use fixed-size arrays instead of dynamic ones if the size is known.
  • Refactor logic to avoid loops or reduce iterations.
  • Consider a pull-based system for payouts instead of pushing to many recipients in one transaction.

Using `view` and `pure` Functions

Functions marked as view or pure do not modify the blockchain state. When called externally, they don't cost any gas!

  • view: Reads state variables but doesn't modify them.
  • pure: Neither reads nor modifies state variables.

Internal calls to view/pure functions still consume gas (as part of the larger transaction), but using them correctly for external queries is a huge gas saver for users.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ViewPureExample {
    uint256 public myNumber = 42;

    // Costs no gas for external calls
    function getNumber() public view returns (uint256) {
        return myNumber;
    }

    // Costs no gas for external calls
    function add(uint256 a, uint256 b) public pure returns (uint256) {
        return a + b;
    }
}

Error Handling Gas Costs

Solidity provides several ways to handle errors: require(), revert(), and assert().

  • require(): Used for validating inputs and conditions. Refunds unused gas when it fails. (Recommended for most checks)
  • revert(): Similar to require, also refunds unused gas.
  • assert(): Used for internal invariants and should *never* fail. Consumes ALL remaining gas when it fails. (Use sparingly for critical internal checks)

Failing an assert is much more expensive than failing a require, so choose your error handling wisely.

Question: Gas Optimization

Consider the following Solidity snippet. Which change would likely lead to the MOST significant gas savings for a user calling updateStatus?

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract GasPuzzle {
    uint256 public statusId;
    string public statusName;
    address public owner;

    constructor() {
        owner = msg.sender;
        statusId = 1;
        statusName = "Initial";
    }

    function updateStatus(uint256 _newId, string memory _newName) public {
        require(msg.sender == owner, "Not owner");
        statusId = _newId;
        statusName = _newName;
    }
}

Recap: Gas Optimization Mastery

You've unlocked key strategies for writing gas-efficient Solidity code!

Remember these principles:

  • Minimize Storage Writes: The golden rule.
  • Pack Variables: Group smaller variables to fit slots.
  • Use Efficient Data Locations: Prefer calldata/memory over storage.
  • Optimize Loops: Avoid unbounded or large iterations.
  • Leverage view/pure: For gas-free external reads.
  • Smart Error Handling: Use require/revert, not assert for user input.

Applying these techniques will lead to more affordable, faster, and user-friendly DApps. Keep practicing!

คำถามที่พบบ่อย

บทเรียน “เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Web3 & DApp Development Fundamentals ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Web3 & DApp Development Fundamentals มีบทเรียนทั้งหมด 3 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส”

เรียนรู้กลยุทธ์การเขียนโค้ด Solidity ให้ใช้แก๊สอย่างมีประสิทธิภาพ เพื่อลดต้นทุนธุรกรรมและเพิ่มประสิทธิภาพของ DApp บนบล็อกเชน คุณปฏิบัติ Web3 & DApp Development Fundamentals ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Web3 & DApp Development Fundamentals หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Web3 & DApp Development Fundamentals บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 3 บทเรียน

บทเรียน “เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Web3 & DApp Development Fundamentals นี้ได้ไหม

ได้ บทเรียน Web3 & DApp Development Fundamentals ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. ช่องโหว่ทั่วไปของสัญญาอัจฉริยะ
  2. เครื่องมือและการตรวจสอบความปลอดภัย
  3. เทคนิคการเพิ่มประสิทธิภาพการใช้แก๊ส
← กลับไปที่ Web3 & DApp Development Fundamentals