Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
molly-ting opened this issue Aug 23, 2023 · 1 comment
Open

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

molly-ting opened this issue Aug 23, 2023 · 1 comment

Comments

@molly-ting
Copy link
Contributor

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];
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants
@molly-ting and others