The increment in for loop post condition can be made unchecked #232
Labels
bug
Warden finding
G (Gas Optimization)
sponsor acknowledged
Technically the issue is correct, but we're not going to resolve it for XYZ reasons
Handle
hrkrshnn
Vulnerability details
The increment in for loop post condition can be made unchecked
(This is only relevant if you are using the default solidity checked
arithmetic.)
Consider the following generic for loop:
In this example, the for loop post condition, i.e.,
i++
involveschecked arithmetic, which is not required. This is because the value of
i
is always strictly less thanlength <= 2**256 - 1
. Therefore, thetheoretical maximum value of
i
to enter the for-loop body is `2**256. This means that the
i++` in the for loop can never overflow.Regardless, the overflow checks are performed by the compiler.
Unfortunately, the Solidity optimizer is not smart enough to detect this
and remove the checks. One can manually do this by:
Note that it's important that the call to
unchecked_inc
is inlined.This is only possible for solidity versions starting from
0.8.2
.Gas savings: roughly speaking this can save 30-40 gas per loop
iteration. For lengthy loops, this can be significant!
Examples
The text was updated successfully, but these errors were encountered: