Looping over array with array length as condition

Viewed 1600

Say we have a contract with a dynamic state array fooArray of uint256. At the same contract there is a function with the following loop:

for (uint256 i = 0; i < fooArray.length; ++i) {
// Some code here, that does not modify array in any way.
}

Does checking the loop condition require reading the length of the fooArray from the storage on each iteration or it is not considered as reading a value from the storage?
Should I preliminarily save length of the array to a local variable and use this variable as a loop condition to save gas?

1 Answers

I created new contract and then executed it 3 times without temp variable and then again created new contract and executed with temp variable. Results from Remix Javscript VM and Rinkeby networks were precisely the same and function with temp variable required less gas. It is possible to read bytecode and Gas Costs from Yellow Paper however I think it is quite clear that it is better to use temp variable.

Solidity code:

pragma solidity ^0.8.0;
 
contract EstimateGas {
    uint[] public fooArray;
    constructor (){
        for (uint256 i = 0; i < 500; ++i) {
            fooArray.push(i);
        }
    }
    function changeNoTemp() public{
        for (uint256 i = 0; i < fooArray.length; ++i) {
            fooArray[i] = fooArray[i] +1;
        }        
    }
    function changeWithTemp() public{
        uint arrayLen = fooArray.length;
        for (uint256 i = 0; i < arrayLen; ++i) {
            fooArray[i] = fooArray[i] +1;
        }        
    }    
}

Gas execution costs

changeNoTemp()
1) 2965426 gas
2) 2948326 gas
3) 2948326 gas

changeWithTemp()
1) 2911461 gas
2) 2894361 gas
3) 2894361 gas
Related