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++) {
}
}
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.PR Checklist
npx changeset add
)