Closed code423n4 closed 3 years ago
Would not take the gas savings at face value as some of the numbers apply only for storage
That said, caching the length does actually save gas (3 gas from memory) because to retrieve array.length you need to perform a math operation to get the memory position in which the length is stored
Duplicate of #230
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