Skip to content

move loop invariant code out from loop to save gas #9

Description

@molly-ting

Moving loop invariant codes out from loop can save gas.
In the following demo, it can save 765 units of gas when the length of arr is 100.

    function test1(uint256[] calldata arr) public {     
        for(uint256 i = 0; i < arr.length; i++) {
        }
    }

    function test2(uint256[] calldata arr) public {
        uint256 len = arr.length;
        for(uint256 i = 0; i < len; i++) {
        }
    }

In function _applyFractionsAndTransferEach in lib/OrderFulfiller.sol, orderParameters.offerer and orderParameters.conduitKey are not changed in loop.

Initializing variables before the loop instead of inside the loop can also save gas. In the example below, function test4 consumes 553 units less gas than function test3 when the length of arr is 100.

    function test3(uint256[] memory arr) public {
        for(uint256 i = 0; i < arr.length; i++) {
            uint256 a = arr[i];
        }
    }

    function test4(uint256[] memory arr) public {
        uint256 a;
        for(uint256 i = 0; i < arr.length; i++) {
            a = arr[i];
        }
    }

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions