Loop increments
Rushank Savant
Posted on May 5, 2022
This is a very simple technique which many of us might be using without knowing it's gas efficient.
Consider the following contracts:
contract Inc1{
uint[] public arr = [0,1,2,3,4,5,6,7,8,9,10];
uint total;
function something() external {
uint sum;
uint[] memory _arr = arr;
for (uint i; i < _arr.length; i += 1) {
sum += _arr[i];
}
total = sum;
}
}
contract Inc2{
uint[] public arr = [0,1,2,3,4,5,6,7,8,9,10];
uint total;
function something() external {
uint sum;
uint[] memory _arr = arr;
for (uint i; i < _arr.length; i++) {
sum += _arr[i];
}
total = sum;
}
}
Both the contracts have function something
which iterates through the array to sum all the elements. But the difference is in the increment style of loops. Inc1 has i +=1
while Inc2 has i++
Inc1
Inc2
💖 💪 🙅 🚩
Rushank Savant
Posted on May 5, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.