Gas Optimizations #297
Labels
bug
Something isn't working
duplicate
This issue or pull request already exists
G (Gas Optimization)
1. Cache array length outside of loop
Impact
Caching the array length outside a loop saves reading it on each iteration, as long as the array's length is not changed during the loop.
Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to cache the array length outside of for loop.
2. Long revert error messages
Impact
Shortening revert error messages to fit in 32 bytes will decrease gas costs for deployment and gas costs when the revert condition has been met.
Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to decrease revert messages to maximum 32 bytes. Alternatively custom error types should be used.
3. Use custom errors instead of revert strings to save gas
Impact
Usage of Custom Errors reduces the gas cost.
Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to add Custom Errors.
4. ++i/--i costs less gas compared to i++, i += 1, i-- or i -= 1
Impact
++i
or--i
costs less gas compared toi++
,i += 1
,i--
ori -= 1
for unsigned integer as pre-increment/pre-decrement is cheaper (about 5 gas per iteration).Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to use
++i
or--i
instead ofi++
,i += 1
,i--
ori -= 1
to increment value of an unsigned integer variable.5. Obsolete overflow/underflow check
Impact
Starting from solidity
0.8.0
there is built-in check for overflows/underflows. This mechanism automatically checks if the variable overflows or underflows and throws an error. Multiple contracts use increments that cannot overflow but consume additional gas for checks.Proof of Concept
Recommended Mitigation Steps
It is recommended wrap incrementing of
i
withunchecked
blockunchecked { ++i }
orunchecked { --i }
.6. No need to explicitly initialize variables with default values
Impact
If a variable is not set/initialized, it is assumed to have the default value (
0
for uint,false
for bool,address(0)
for addresses). Explicitly initializing it with its default value is an anti-pattern and waste of gas.Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to remove explicit initializations with default values.
7. Use != 0 instead of > 0 for unsigned integer comparison
Impact
When dealing with unsigned integer types, comparisons with
!= 0
are cheaper that with> 0
.Proof of Concept
Tools Used
Manual Review / VSCode
Recommended Mitigation Steps
It is recommended to use
!= 0
instead of> 0
.The text was updated successfully, but these errors were encountered: