OpenZeppelin / openzeppelin-contracts-upgradeable

Upgradeable variant of OpenZeppelin Contracts, meant for use in upgradeable contracts.
https://openzeppelin.com/contracts
MIT License
1k stars 436 forks source link

move loop invariant variables out from loop to save gas #198

Closed molly-ting closed 1 year ago

molly-ting commented 1 year ago

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++) {
        }
    }

PR Checklist

songlh commented 1 year ago

@nventuro can you take a look at this pull request? it looks good to me. The original functionality is preserved and some gases can be saved.

songlh commented 1 year ago

Can anyone take a look at this pull request?

frangio commented 1 year ago

https://github.com/OpenZeppelin/openzeppelin-contracts/pull/4182#issuecomment-1586310971