i++ is generally more expensive because it must increment a value and return the old value,
so it may require holding two numbers in memory. ++i only uses one number in memory.
Example:
for (uint256 i = 0; i < poolInfo.length; i++) -> for (uint256 i = 0; i < poolInfo.length; i++)
(LPFarming 348)
No need to explicitly initialize variables with default values
If a variable is not initialized it is automatically set to the default value (0 for uint, false for bool, address(0) for address...).
Explicitly initializing it with its default value is an anti-pattern and wastes gas.
Example:
for (uint256 i = 0; i < poolInfo.length; i++) -> for (uint256 i; i < poolInfo.length; i++)
Gas optimizations
Change i++ to ++i
i++ is generally more expensive because it must increment a value and return the old value, so it may require holding two numbers in memory. ++i only uses one number in memory.
Example:
for (uint256 i = 0; i < poolInfo.length; i++) -> for (uint256 i = 0; i < poolInfo.length; i++)
(LPFarming 348)Affected contracts: LPFarming.sol, NFTVault.sol, StrategyPUSDConvex.sol
No need to explicitly initialize variables with default values
If a variable is not initialized it is automatically set to the default value (0 for uint, false for bool, address(0) for address...). Explicitly initializing it with its default value is an anti-pattern and wastes gas.
Example:
for (uint256 i = 0; i < poolInfo.length; i++) -> for (uint256 i; i < poolInfo.length; i++)
Affected contracts: LPFarming.sol, NFTVault.sol, StrategyPUSDConvex.sol
Loop storage/memory acess cache
Calling storage/memory variable which does not change, every loop iteration, is wrong and wastes gas.
for (uint256 i = 0; i < poolInfo.length; i++)
->uint256 length = poolInfo.length;
for (uint256 i = 0; i < length; i++)
Affected contracts: LPFarming.sol, NFTVault.sol, StrategyPUSDConvex.sol
Use calldata
Use calldata instead of memory for external functions where the function argument is read-only.
function setBorrowAmountCap(uint256 _borrowAmountCap) external
->function setBorrowAmountCap(uint256 calldata _borrowAmountCap) external
Affected contracts: Neary every contract
Variables should be immutable
Some variables could be set immutable to save gas
collateralAsset
in FungibleAssetVaultForDAO_collateralUnit
in FungibleAssetVaultForDAOUnused import
unused import wastes gas.
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
in NFTEscrow