sload loads a word from storage. https://ethereum.github.io/yellowpaper/paper.pdf
if we have a loop over uint256
, both preloading into memory and loading within the loop should use the same number sload calls. I assume when loading into memory, there is a loop over sload calls. so why is preloading a bit faster?
modifying https://moralis.io/gas-optimizations-in-solidity-top-tips/ :
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Gas_Test{
uint[] public arrayFunds;
uint public totalFunds;
constructor() {
arrayFunds = [1,2,3,4,5,6,7,8,9,10,11,12,13,2,3,4,5,6,7,8,9,10,11,12,13];
}
function optionB2() external {
uint _totalFunds;
uint al = arrayFunds.length;
for (uint i =0; i < al; i++){
_totalFunds = _totalFunds + arrayFunds[i];
}
totalFunds = _totalFunds;
}
function optionC() external {
uint _totalFunds;
uint[] memory _arrayFunds = arrayFunds;
for (uint i =0; i < _arrayFunds.length; i++){
_totalFunds = _totalFunds + _arrayFunds[i];
}
totalFunds = _totalFunds;
}
}
B2 is 105997 gas C is 104084 gas
if i use an array that is almost half the size arrayFunds = [1,2,3,4,5,6,7,8,9,10,11,12,13]
, the gas difference almost halves:
B2 is 69275
C is 68396
the cost of sload is 2100. the difference is smaller than a sload. However, b2 makes 4 sload calls, and C makes only 2. I'd think memory would have to do a bunch of calls to load the whole array.