Solidity – Do SLOAD Operations Get Cached in Solidity to Optimize Gas Usage?

gassolidity

When I access an unchanged value from storage multiple times, in the same function or transaction, does it get cached, or do I pay the SLOAD cost for each time I access it?

I can easily cache it in memory if not, but I'm not sure if I need to or not.

Best Answer

By using a very simple test contract:

contract Test {
    uint one = 1;
    function test() returns (uint){
        return one + one;
    }
} 

then using the debugger built into Remix, we can see that in fact there are two SLOAD calls.

Thus, no, these types of storage variables are not cached in any way, and it may be worth doing so manually.