บทเรียนที่ 5

Smart Contract Optimization Finale - Advanced Tips and Tricks

In our previous lessons, we've covered foundational concepts and tools you need to optimize gas on Ethereum smart contracts, especially using the Remix IDE. As we wrap up this course, let's delve into some advanced techniques and best practices. This final lesson will combine the knowledge we've accumulated, ensuring that you walk away with a well-rounded understanding of gas optimization in Ethereum smart contracts.

Refactoring and Reducing Code Complexity

One of the most straightforward ways to save gas is by making your code simpler. The less code there is to execute, the less gas is consumed.

Practice Example

Consider the following function:

Solidity
pragma solidity ^0.8.9;

contract OptimizationExample {
    address[] public admins;

    function isUserAdmin(address user) public view returns (bool) {
        for (uint i = 0; i < admins.length; i++) {
            if (admins[i] == user) return true;
        }
        return false;
    }
}

The above function uses a loop, which becomes more costly as more admins are added. A more gas-efficient structure would use a mapping:

Solidity
contract OptimizationExampleOptimized {
    mapping(address => bool) public admins;

    function isUserAdmin(address user) public view returns (bool) {
        return admins[user];
    }
}

Reuse Data

When working with Ethereum, remember that you’re paying for every bit of storage. If you find yourself storing the same data in multiple places, consider how you might store it once and reference it elsewhere.

Use Libraries

Libraries in Solidity are reusable pieces of code. They can help you write modular code, and since they are deployed only once and linked to other contracts, they can save gas in the long run.

Solidity
library SafeMath {
    function add(uint a, uint b) internal pure returns (uint) {
        uint c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }
    //... other math functions
}

contract UsingSafeMath {
    using SafeMath for uint;

    uint public value;

    function increment(uint _value) public {
        value = value.add(_value);
    }
}

Delete Unnecessary Storage

The delete keyword in Solidity allows you to nullify variables, which refund some of the gas. If you’re finished with a particular piece of storage, delete it to claim this refund.

Consider Event Logs

While storing data on the blockchain can be costly, logging events is comparatively cheaper. If you have data that doesn’t need to be read from the contract but should be verifiable, consider using event logs.

Avoid Using Expensive Operations

Some operations are more gas-intensive than others. For instance:

  • External function calls are more expensive than internal ones.
  • Interacting with storage is more expensive than interacting with memory.
  • Dynamic arrays can sometimes cost more gas than fixed-size arrays.

Conclusion

Smart contract optimisation for gas is both an art and a science. The approaches discussed in this course, when combined, have the potential to drastically lower the gas costs of your contracts. Keep in mind that the Ethereum ecosystem and its tools, including Remix, are always changing. Keep up to date, and test and improve your contracts on a regular basis for optimisation. The Ethereum community is large and helpful, so never be afraid to seek guidance or best practices. Have fun coding!

ข้อจำกัดความรับผิด
* การลงทุนคริปโตมีความเสี่ยงสูง โปรดดำเนินการด้วยความระมัดระวัง หลักสูตรนี้ไม่ได้มีไว้เพื่อเป็นคำแนะนำในการลงทุน
* หลักสูตรนี้สร้างขึ้นโดยผู้เขียนที่ได้เข้าร่วม Gate Learn ความคิดเห็นของผู้เขียนไม่ได้มาจาก Gate Learn
แคตตาล็อก
บทเรียนที่ 5

Smart Contract Optimization Finale - Advanced Tips and Tricks

In our previous lessons, we've covered foundational concepts and tools you need to optimize gas on Ethereum smart contracts, especially using the Remix IDE. As we wrap up this course, let's delve into some advanced techniques and best practices. This final lesson will combine the knowledge we've accumulated, ensuring that you walk away with a well-rounded understanding of gas optimization in Ethereum smart contracts.

Refactoring and Reducing Code Complexity

One of the most straightforward ways to save gas is by making your code simpler. The less code there is to execute, the less gas is consumed.

Practice Example

Consider the following function:

Solidity
pragma solidity ^0.8.9;

contract OptimizationExample {
    address[] public admins;

    function isUserAdmin(address user) public view returns (bool) {
        for (uint i = 0; i < admins.length; i++) {
            if (admins[i] == user) return true;
        }
        return false;
    }
}

The above function uses a loop, which becomes more costly as more admins are added. A more gas-efficient structure would use a mapping:

Solidity
contract OptimizationExampleOptimized {
    mapping(address => bool) public admins;

    function isUserAdmin(address user) public view returns (bool) {
        return admins[user];
    }
}

Reuse Data

When working with Ethereum, remember that you’re paying for every bit of storage. If you find yourself storing the same data in multiple places, consider how you might store it once and reference it elsewhere.

Use Libraries

Libraries in Solidity are reusable pieces of code. They can help you write modular code, and since they are deployed only once and linked to other contracts, they can save gas in the long run.

Solidity
library SafeMath {
    function add(uint a, uint b) internal pure returns (uint) {
        uint c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }
    //... other math functions
}

contract UsingSafeMath {
    using SafeMath for uint;

    uint public value;

    function increment(uint _value) public {
        value = value.add(_value);
    }
}

Delete Unnecessary Storage

The delete keyword in Solidity allows you to nullify variables, which refund some of the gas. If you’re finished with a particular piece of storage, delete it to claim this refund.

Consider Event Logs

While storing data on the blockchain can be costly, logging events is comparatively cheaper. If you have data that doesn’t need to be read from the contract but should be verifiable, consider using event logs.

Avoid Using Expensive Operations

Some operations are more gas-intensive than others. For instance:

  • External function calls are more expensive than internal ones.
  • Interacting with storage is more expensive than interacting with memory.
  • Dynamic arrays can sometimes cost more gas than fixed-size arrays.

Conclusion

Smart contract optimisation for gas is both an art and a science. The approaches discussed in this course, when combined, have the potential to drastically lower the gas costs of your contracts. Keep in mind that the Ethereum ecosystem and its tools, including Remix, are always changing. Keep up to date, and test and improve your contracts on a regular basis for optimisation. The Ethereum community is large and helpful, so never be afraid to seek guidance or best practices. Have fun coding!

ข้อจำกัดความรับผิด
* การลงทุนคริปโตมีความเสี่ยงสูง โปรดดำเนินการด้วยความระมัดระวัง หลักสูตรนี้ไม่ได้มีไว้เพื่อเป็นคำแนะนำในการลงทุน
* หลักสูตรนี้สร้างขึ้นโดยผู้เขียนที่ได้เข้าร่วม Gate Learn ความคิดเห็นของผู้เขียนไม่ได้มาจาก Gate Learn