identified-optimizations.md

March 5, 2023 · View on GitHub

 

⚡Identified Gas Optimizations

Below are the currently identified optimizations that solstat identifies. If you would like to check out a list of patterns that are ready to be implemented and you would like to add them to the repo, you can check out the Contribution.md!

OptimizationDescription
address_balanceUse selfbalance() instead of address(this).balance.
address_zeroUse assembly to check for address(0).
assign_update_array_valueWhen updating a value in an array with arithmetic, using array[index] += amount is cheaper than array[index] = array[index] + amount. This optimization also catches other arithmetic, bitwise and other operations.
bool_equals_boolInstead of if (x == bool), use if(x) or when applicable, use assembly with iszero(iszero(x)).
cache_array_lengthCache array length during for loops.
constant_variablesMark storage variables as constant if they never change and are not marked as constants.
immutable_variablesMark storage variables as immutable if variables are assigned during deployment and never change afterwards.
increment_decrementUse unchecked{++i} instead of i++, or ++i (or use assembly when applicable). This also applies to decrementing as well.
memory_to_calldataUse calldata for function arguments marked as memory that do not get mutated.
multiple_requireUse multiple require() statements instead of require(expression && expression && ...).
optimal_comparisonUse strict > & < operators over >= & <= operators.
pack_storage_variablesTightly pack storage variables for efficient contract storage.
pack_struct_variablesTightly pack struct variables for efficient contract storage.
payable_functionMark functions as payable (with discretion).
private_constantMark constant variables in storage as private to save gas.
safe_math_post_080Identifies when SafeMath is being used if the contract using solidity >= 0.8.0. Using SafeMath when using version >= 0.8.0 is redundant and will incur additional gas costs.
safe_math_pre_080Identifies when SafeMath is being used if the contract using solidity < 0.8.0. Consider using assembly with overflow/undeflow protection for math (add, sub, mul, div) instead of SafeMath.
shift_mathRight shift or Left shift instead of dividing or multiplying by powers of two.
short_revert_stringUse revert strings that fit in one word.
solidity_keccak256Use assembly to hash instead of Solidity.
solidity_mathUse assembly for math (add, sub, mul, div).
sstoreUse assembly to write storage values.
string_errorUse custom errors instead of string error messages for contracts using Solidity version >= 0.8.4.