Skip to main content

Cache Array Length In For Loops Can Save Gas

Description

In Solidity, it is common to use for loops to iterate through arrays. However, accessing the length of an array on each iteration of a loop can consume unnecessary gas. To optimize this, you can cache the array length in a variable before the loop and use that variable as the loop condition. When the length of an array is read at each iteration of the loop, it requires 6 gas (3 for mload and 3 to place memory_offset) onto the stack. Caching the length of the array on the stack saves about 3 gas per iteration.

Example Code

Consider the following example of a function that iterates over an array of integers to calculate their sum:

function sumArray(uint[] memory arr) public view returns (uint) {
uint sum = 0;
for (uint i = 0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}

In this example, the loop condition i < arr.length is evaluated on each iteration, which adds unnecessary gas cost.

To optimize this, we can cache the length of the array in a variable before the loop:

function sumArray(uint[] memory arr) public view returns (uint) {
uint sum = 0;
uint len = arr.length;
for (uint i = 0; i < len; i++) {
sum += arr[i];
}
return sum;
}

By caching the length of the array in the len variable, we can avoid the extra gas cost of accessing arr.length on each iteration.

Recommendation

To optimize gas usage in Solidity functions that iterate over arrays, consider caching the length of the array in a variable before the loop and using that variable as the loop condition. This can save gas by avoiding the extra cost of accessing the array length on each iteration.