Gas Optimizations #273
Labels
bug
Something isn't working
duplicate
This issue or pull request already exists
G (Gas Optimization)
Gas
[G-01] Use
!= 0
instead of> 0
for Unsigned Integer Comparison in require statements.Impact
!= 0
is cheapear than> 0
when comparing unsigned integers in require statements.Proof of Concept
Recommendation
Use
!= 0
instead of> 0
.[G-02] Cache Array Length Outside of Loop.
Impact
Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack. Caching the array length in the stack saves around 3 gas per iteration.
Proof of Concept
Recommendation
Store the array’s length in a variable before the for-loop.
[G-03]
++i
costs less gas compared toi++
ori += 1
Impact
++i
costs less gas compared toi++
ori += 1
for unsigned integer, as pre-increment is cheaper (about 5 gas per iteration). This statement is true even with the optimizer enabled.Proof of Concept
Recommendation
Use
++i
instead ofi++
to increment the value of an uint variable.Same thing for
--i
andi--
.[G-04] No need to initialize variables with default values
Impact
If a variable is not set/initialized, it is assumed to have the default value (0, false, 0x0 etc depending on the data type). Explicitly initializing it with its default value is an anti-pattern and wastes gas.
Proof of Concept
Recommendation
Remove explicit default initializations.
[G-05] Non-strict inequalities are cheaper than strict ones
Impact
Strict inequalities add a check of non equality which costs around 3 gas.
Proof of Concept
Throughout codebase.
Recommendation
Use
>=
or<=
instead of>
and<
when possible.Tools used
c4udit, manual, slither
The text was updated successfully, but these errors were encountered: