move loop invariant variables out from loop
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)
🦋 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
@nventuro @frangio @Amxx Can you help take a look at this pull request?
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.