1. array length in loops can be cached instead of calculating in every iteration
The loop bounds are calculated with array.length which are calculated in every loop iterations which can result in high gas.
The array length can be cached instead of calculating in every loop iteration to save gas.
// Before
for (uint i = 0; i < amounts.length; i++) {
}
// After
uint len = amounts.length;
for (uint i = 0; i < len; i++) {
}
The instances where this pattern can be applied is found as follows
> grep -rn './contracts/tokenomics' -e 'for.*[.]length'
./contracts/tokenomics/FeeBurner.sol:59: for (uint256 i; i < tokens_.length; i = i.uncheckedInc()) {
./contracts/tokenomics/VestedEscrow.sol:94: for (uint256 i; i < amounts.length; i = i.uncheckedInc()) {
./contracts/tokenomics/InflationManager.sol:119: for (uint256 i; i < stakerVaults.length; i = i.uncheckedInc()) {
2. Use solidity custom errors to save gas
solidity 0.8.4 introduces custom errors which are cheaper than using revert strings in terms of gas
Use the custom error patterns to reduce gas cost.
for eg.
// Before
require(condition, "Revert strings");
// After
error CustomError();
if (!condition) {
revert CustomError();
}
1. array length in loops can be cached instead of calculating in every iteration
The loop bounds are calculated with
array.length
which are calculated in every loop iterations which can result in high gas. The array length can be cached instead of calculating in every loop iteration to save gas.The instances where this pattern can be applied is found as follows
2. Use solidity custom errors to save gas
solidity 0.8.4 introduces custom errors which are cheaper than using revert strings in terms of gas Use the custom error patterns to reduce gas cost.
for eg.
more details can be found here
3.
!=0
is cheaper than>0
!=0
is cheaper than using>0
for uints