DEV Community

Rushank Savant
Rushank Savant

Posted on • Edited on

3 3

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs