compound-finance / compound-protocol

The Compound On-Chain Protocol
https://compound.finance/developers
BSD 3-Clause "New" or "Revised" License
1.89k stars 1.21k forks source link

Gas optimization #227

Open molly-ting opened 2 years ago

molly-ting commented 2 years ago

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);
    }
}
Tcola0f commented 2 years ago

sorry

songlh commented 2 years ago

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

Tcola0f commented 2 years ago

please disregard