Suppose a function writes to storage, and then reads from the same storage location before it has been overwritten. In solidity 0.8.11 in these cases the SLOAD
gets optimized away (there is 1 SSTORE
and 0 SLOAD
):
uint256 private x;
function test() external returns (uint256) {
x = 5;
return x;
}
uint256[1] private x;
function test() external returns (uint256) {
x[0] = 5;
return x[0];
}
But in this (only a little bit more complex) case it does not (there is 1 SSTORE
and 1 SLOAD
):
uint256[1] private x;
function test(uint256 i) external returns (uint256) {
x[i] = 5;
return x[i];
}
With SLOAD cost having been increased from 200 to 800 it seems quite important.
In which cases is the SLOAD
guaranteed to get optimized away?
Should we always manually optimize this?