While reading 2 articles about this topic and they both expimine the same example, I still can't understand what is going on:
- https://coinsbench.com/solidity-gas-optimization-1-understanding-how-evm-works-can-save-you-gas-44c87011b295
- https://coinsbench.com/advanced-gas-optimizations-tips-for-solidity-85c47f413dc5
Questions
- Does cold access means simply accessing storage?
- Does hot access means simply accessing memory?
- 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 be1200*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
andNotCaching
is thatmyArray.length
is read 10 times inCaching
from storage, while inNotCaching
it's from memory (so even cheaper than warm storage). In both cases the elements ofmyArray
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 multiplekeccak256
calculations of the state slots in the loop.You can write better examples on remix, for example I made this:
You can see that adding a warm read adds around 100 gas, while a cold one over 1000.