If a state variable is read immediately after assignment, then replacing this read directly with the previously assigned local variable will change one SLOAD to one MLOAD to save some gases. In the following example, function test0 costs 188 more gases than function test1 and function test2 costs 203 more gases than function test3.
contract Demo {
uint public sa;
address public add;
event opUpdate(uint b);
event addUpdate(address c);
function test0(uint va) public {
sa = va;
emit opUpdate(sa);
}
function test1(uint va) public {
sa = va;
emit opUpdate(va);
}
function test2() public {
add = msg.sender;
emit addUpdate(add);
}
function test3() public {
add = msg.sender;
emit addUpdate(msg.sender);
}
}
If a state variable is read immediately after assignment, then replacing this read directly with the previously assigned local variable will change one SLOAD to one MLOAD to save some gases. In the following example, function test0 costs 188 more gases than function test1 and function test2 costs 203 more gases than function test3.