Skip to content

Conversation

@grGred
Copy link

@grGred grGred commented Jul 17, 2022

For loop can be gas optimized by adding uint i in for loop.

Example and gas estimation:

    function loopCheck1(uint256[] memory arr) external returns (uint256[] memory) {
        gas = gasleft(); // 29863 gas
        uint length = arr.length;
        for (uint i; i < length;) {
            unchecked { ++i; }
        }
        return arr;
        gas -= gasleft();
    }
    
    function loopCheck2(uint256[] memory arr) external  returns (uint256[] memory) {
        gas = gasleft();
        uint i;
        uint length = arr.length;
        for (; i < length;) { // 29912 gas
            unchecked { ++i; }
        }
        return arr;
        gas -= gasleft();
    }

You can check my article about gas optimizations

I also used prettier. And, maybe, memory arrays could be changed into calldata.

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

Successfully merging this pull request may close these issues.

1 participant