Solidity and Gas Optimization – Cold Access VS Warm Access: Understanding Gas Cost Differences

gassolidity

While reading 2 articles about this topic and they both expimine the same example, I still can't understand what is going on:

enter image description here

Questions

  1. Does cold access means simply accessing storage?
  2. Does hot access means simply accessing memory?
  3. The total gass cost difference between the 2 examples are in the NonCaching example: 51,209 - 49,657 = 1,552 gas. If each cold access cost 1200 gas, how can it be right if the first example access the cold storage every loop and it cost 1200 gas each read? The diff should be 1200*10 (myArray.length 10 times) + 1200*10 (myArray[i] 10 times) = 1200*20.

Best Answer

Those articles didn't use a good example to explain the situation, that's why you are confused.

Cold/warm access refers always to storage, never to memory. You have cold access the first time you read a variable, warm access when you read it again.

The only difference between the methods Caching and NotCaching is that myArray.length is read 10 times in Caching from storage, while in NotCaching it's from memory (so even cheaper than warm storage). In both cases the elements of myArray are read each once (so cold access in both). The difference in gas should be then around 10*100 = 1000. The extra 500 is probably due to multiple keccak256 calculations of the state slots in the loop.

You can write better examples on remix, for example I made this:

contract ColdWarmGas {
    uint256 x = 1;  // storage variable
    uint256 y = 2;  // storage variable

    // 2381 gas
    function test1() external view returns (uint256 a) {
        a = x;      // cold read
        a = a + x;  // warm read
    }

    // 4473 gas
    function test2() external view returns (uint256 a) {
        a = x;      // cold read
        a = a + y;  // cold read
    }

    // 4632 gas
    function test3() external view returns (uint256 a) {
        a = x;      // cold read
        a = a + y;  // cold read
        a = a + y;  // warm read
    }
}

You can see that adding a warm read adds around 100 gas, while a cold one over 1000.

Related Topic