rushanksavant

Rushank Savant

Posted on May 5, 2022

Loop increments

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Image description

Inc2

Image description

💖 💪 🙅 🚩
rushanksavant
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.

Related

Variable sequence - 2
solidity Variable sequence - 2

May 13, 2022

Loop increments
solidity Loop increments

May 5, 2022

Short-circuiting
solidity Short-circuiting

May 4, 2022