Consider a generic example of an array arr and the following loop:
for (uint i = 0; i < arr.length; i++) {
// do something that doesn't change arr.length
}
In the above case, the solidity compiler will always read the length of
the array during each iteration. That is, if it is a storage array, this
is an extra sload operation (100 additional extra gas for each
iteration except for the first) and if it is a memory array, this is an
extra mload operation (3 additional gas for each iteration except for
the first).
This extra costs can be avoided by caching the array length (in stack):
uint length = arr.length;
for (uint i = 0; i < length; i++) {
// do something that doesn't change arr.length
}
In the above example, the sload or mload operation is only done once
and subsequently replaced by a cheap dupN instruction.
This optimization is especially important if it is a storage array or if
it is a lengthy for loop.
Note that the Yul based optimizer (not enabled by default; only relevant
if you are using --experimental-via-ir or the equivalent in standard
JSON) can sometimes do this caching automatically. However, this is
likely not the case in your project.
Examples
./contracts/v3/Vault.sol:199: for (uint8 i; i < _amounts.length; i++) {
./contracts/v3/Vault.sol:299: for (uint8 i; i < _tokens.length; i++) {
./contracts/v3/VaultHelper.sol:64: for (uint8 i = 0; i < _amounts.length; i++) {
./contracts/v3/controllers/Controller.sol:458: for (uint i = 0; i < _strategies.length; i++) {
Handle
hrkrshnn
Vulnerability details
Caching the length in for loops
Consider a generic example of an array
arr
and the following loop:In the above case, the solidity compiler will always read the length of the array during each iteration. That is, if it is a storage array, this is an extra
sload
operation (100 additional extra gas for each iteration except for the first) and if it is a memory array, this is an extramload
operation (3 additional gas for each iteration except for the first).This extra costs can be avoided by caching the array length (in stack):
In the above example, the
sload
ormload
operation is only done once and subsequently replaced by a cheapdupN
instruction.This optimization is especially important if it is a storage array or if it is a lengthy for loop.
Note that the Yul based optimizer (not enabled by default; only relevant if you are using
--experimental-via-ir
or the equivalent in standard JSON) can sometimes do this caching automatically. However, this is likely not the case in your project.Examples