Gas optimization Series Part -2

Saksham ThapaSaksham Thapa
2 min read

Today we'll briefly look into caching state variables

It is always better to cache a state variable if you can. What does caching a state variable even mean? It's a jargon word to scare off people. In essence, it's simply the act of copying state variable value to a local variable that resides in memory. Accessing a state variable uses SLOAD opcode which uses 100 gas for each load operation. Whereas accessing a local memory variable executes MLOAD opcode which only uses only 3 gas. That can make a huge difference if you're iterating over a list.

Let's look at the example:

pragma solidity 0.8.17;

contract MyContract{
    uint256 counter;

    function noCache() public {
        for(uint i =0; i < 100; i++){
            counter += 1;
        }
    }    

    function cache() public{
        uint256 cachedCounter = counter;
        for(uint i =0; i < 100; i++){
            cachedCounter += 1;
        }
        counter = cachedCounter;
    }
}

We have a counter state variable and two function that increments the counter 100 times. "noCache()" directly accesses the state variable every iteration, while "cache()" caches the state variable in a local cachedCounter and after the loop stores back to the state variable.

In the first non cached function with no gas the gas cost was:

While for the second cached function the gas cost was:

73997 gas from 118611, Big difference right? So always cache it if you can.

0
Subscribe to my newsletter

Read articles from Saksham Thapa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Saksham Thapa
Saksham Thapa