Gas Optimizations #255
Labels
bug
Something isn't working
duplicate
This issue or pull request already exists
G (Gas Optimization)
Unnecessary checked arithmetic in for loops
There is no risk of overflow caused by increments to the iteration index in for loops (the
i++
infor (uint256 i = 0; i < numIterations; i++)
). Increments perform overflow checks that are not necessary in this case.Recommendation
Surround the increment expressions with an
unchecked { ... }
block to avoid the default overflow checks. For example, change the loopto
It is a little less readable but it saves a significant amount of gas.
Unnecessary MLOADs in for-each loops
There are many for loops that follows this for-each pattern:
In such for loops, the
array.length
is read on every iteration, instead of caching it once in a local variable and read it from there. Memory reads are a bit more expensive than reading local variables.Recommendation
Read these values from memory once, cache them in local variables and then read them again from the local variables. For example:
Prefix increments / decrements are cheaper than postfix increments / decrements
Use prefix increments / decrements (
++x
/--x
) instead of postfix increments / decrements (x++
/x--
).Recommendation
Change all postfix increments / decrements to prefix increments / decrements.
!= 0
is cheaper than> 0
It is more gas efficient to compare variables with
!= 0
than it is with> 0
. These two comparisons are equivalent when the compared variable is an unsigned integer.Recommendation
Change all
> 0
comparisons of unsigned integers to!= 0
comparisons.The text was updated successfully, but these errors were encountered: