compound-protocol icon indicating copy to clipboard operation
compound-protocol copied to clipboard

Gas optimization

Open molly-ting opened this issue 3 years ago • 3 comments

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);
    }
}

molly-ting avatar Nov 13 '22 04:11 molly-ting

sorry

Tcola0f avatar Nov 13 '22 19:11 Tcola0f

@jflatow can you take a look at this pull request?

songlh avatar Nov 15 '22 17:11 songlh

please disregard

Tcola0f avatar Nov 15 '22 17:11 Tcola0f