Open code423n4 opened 2 years ago
Nice flag here, we may not be able to use this one as we're already very close to our stack limit (you can see we do significant scoping to get around it). We'll see if this can be applied.
Edit: Did not end up running into stack issues implementing this. It did save us some gas, but less than .1% so I don't think it's worth the extra lines. Thanks for the suggestion!
reopening as per judges assessment as "primary issue" on findings sheet
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