DEV Community

Rushank Savant
Rushank Savant

Posted on • Updated on

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

Latest comments (0)