openzeppelin-contracts icon indicating copy to clipboard operation
openzeppelin-contracts copied to clipboard

move loop invariant variables out from loop

Open molly-ting opened this issue 2 years ago • 1 comments

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

  • [ ] Tests
  • [ ] Documentation
  • [ ] Changeset entry (run npx changeset add)

molly-ting avatar Apr 13 '23 04:04 molly-ting

🦋 Changeset detected

Latest commit: 4a1d4e0323851d97afa7d17d6d5d6f6bc4e80ac7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
openzeppelin-solidity Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

changeset-bot[bot] avatar Apr 13 '23 04:04 changeset-bot[bot]

@nventuro @frangio @Amxx Can you help take a look at this pull request?

songlh avatar Jun 10 '23 17:06 songlh

it can save 765 units of gas when the length of arr is 100.

First of all, I can't reproduce this benchmark. I only see 5 gas difference in total.

Moreover, if it was 765 gas, it would mean less than 8 gas per iteration. This is marginal, we are not interested in such a small optimization.

frangio avatar Jun 11 '23 19:06 frangio