Cache Rule
Dealing with storage variables is expensive, dealing with cached storage variables is cheaper. Ideally, storage variables should be written to and read from no more than once.
Example
pragma solidity ^0.8.17;
uint256 public counter = 1000;
function incrementBy(uint256 amount) external{
for (uint256 i = 0; i < amount; i++) {
counter += 1; // Multiple writes to storage
}
}
function incrementByCached(uint256 amount) external{
uint256 tempCounter = counter; // Single read from storage
for (uint256 i = 0; i < amount; i++) {
tempCounter += 1; // Operations are done on the local variable
}
counter = tempCounter; // Single write back to storage
}
Calling function incrementBy(100)
would cost 4182 gas and calling function incrementByCached(100)
would cost 2161 gas only, proving that cache storage variables help saves almost two times the gas cost.
Test Environment
- Compiler: solc 0.8.17
- Testing Framework: Foundry
ETH saved over 100 transactions
100 tx * 30 gwei * 0.000000001 * (4182-2161) = 0.006063 ~= 0.006 ETH1
USD Saved over 100 transactions
- At \$4000 / ETH: \$24
- At \$3000/ETH: \$18
- At \$2000/ETH: \$12
-
Assumed gas price: 30 gwei ↩