1. Constants and variables read GAS consumption
pragma solidity ^0.8.7;
// 21420 gas
contract demo1{
address public constant admin = 0x6BaB7a0e1696D654adEdf4266B563c7CD656E212;
}
//23553 gas
contract demo2{
address public admin = 0x6BaB7a0e1696D654adEdf4266B563c7CD656E212;
}
Constants consume 2133 Gas less than variables
Reading variables in Ethereum does not need to consume gas fees, but when using write contracts, reading data will consume corresponding Gas fees
In the contract, define as many constants as possible instead of variables according to actual needs
2.if-else and ternary operator
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;
}
}
The gas consumption of the ternary operator is more than if-else, about 40 more gas