DEV Community

Rushank Savant
Rushank Savant

Posted on • Edited on

Avoiding storage access in functions - 1

In many cases accessing data from memory(local variables) is cheaper than accessing data from storage(state variables).

But this might not be always the case, there can be some circumstances where copying to memory can lead to some additional steps.
We will experiment this case in other post.

Let's focus on a general case now. Consider the following contracts:

contract varReferencing_1{
    uint iterations = 10;
    uint public sum;

    function addItem() external {
        for(uint i; i < iterations; i++) { // reference from storage
            sum++; // updating storage
        }
    }

}

contract varReferencing_2{
    uint iterations = 10;
    uint public sum;

    function addItem() external {
        uint _iterations = iterations; // creating a copy in memory
        uint _sum = sum; // creating a copy in memory

        for(uint i; i < _iterations; i++) { // reference from memory
            _sum++; // updating in memory
        }
        sum = _sum; // updating in storage
    }
}
Enter fullscreen mode Exit fullscreen mode

varReferencing_1 and varReferencing_2 both are doing the exact same thing. Only difference is, the addItem() in varReferencing_1 is accessing directly from storage and in varReferencing_2 it's creating copy in memory and then accessing it.

Results:

varReferencing_1 addItem()

Image description

varReferencing_2 addItem()

Image description

Observation:
The gas consumption is reduced while using memory access.

Top comments (0)