Solidity Gas消耗

1.常量和变量读取GAS消耗

pragma solidity ^0.8.7;
// 21420 gas
contract demo1{
    address public constant admin = 0x6BaB7a0e1696D654adEdf4266B563c7CD656E212;
}
//23553 gas
contract demo2{
    address public admin = 0x6BaB7a0e1696D654adEdf4266B563c7CD656E212;
}

常量比变量少消耗2133 Gas费

在以太坊中读取变量不需要消耗gas费,但是当使用写入合约时读取数据就会消耗对应的Gas费

在合约中根据实际需求 尽量多定义常量而不是变量

2.if-else和三元运算符

pragma solidity ^0.8.7;

contract demo{
    //传入参数:1000 21820 gas
    function example_1(uint _x) external pure returns (uint) {
        if (_x <=100){
            return 1;
        }
        else
        {
            return 2;
        }
        
    }
    //传入参数:1000 21861 gas
    function example_2(uint _x) external pure returns (uint){
        return _x <=100 ? 1 : 2;
    }
}

三元运算符的Gas消耗比if-else要更多,大概多了40个gas

猜你喜欢

转载自blog.csdn.net/claysystem/article/details/125543225