3分钟Solidity: 6.7 gas调优

23 阅读1分钟

欢迎订阅专栏3分钟Solidity--智能合约--Web3区块链技术必学

如需获取本内容的最新版本,请参见 Cyfrin.io 上的gas调优技巧(代码示例)

一些 Gas 调优的技巧。

  • 将 memory替换为 calldata
  • 将状态变量加载到内存中
  • 将 for 循环中的 i++替换为 ++i
  • 缓存数组元素
  • 短路运算
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

// gas golf
contract GasGolf {
    // 开始 - 50908 gas
    // 使用 calldata - 49163 gas
    // 将状态变量加载到内存 - 48952 gas
    // 短路 - 48634 gas
    // 循环增量 - 48244 gas
    // 缓存数组长度 - 48209 gas
    // 将数组元素加载到内存 - 48047 gas
    // 不检查 i 溢出/下溢 - 47309 gas

    uint256 public total;

    // 开始 - 未进行gas调优
    // function sumIfEvenAndLessThan99(uint[] memory nums) external {
    //     for (uint i = 0; i < nums.length; i += 1) {
    //         bool isEven = nums[i] % 2 == 0;
    //         bool isLessThan99 = nums[i] < 99;
    //         if (isEven && isLessThan99) {
    //             total += nums[i];
    //         }
    //     }
    // }

    // gas 调优
    // [1, 2, 3, 4, 5, 100]
    function sumIfEvenAndLessThan99(uint256[] calldata nums) external {
        uint256 _total = total;
        uint256 len = nums.length;

        for (uint256 i = 0; i < len;) {
            uint256 num = nums[i];
            if (num % 2 == 0 && num < 99) {
                _total += num;
            }
            unchecked {
                ++i;
            }
        }

        total = _total;
    }
}

Remix Lite 尝试一下

solidity-gas_optimization


END