code-423n4 / 2022-04-jpegd-findings

1 stars 1 forks source link

Gas Optimizations #142

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

1. Caching the length in for loops

impact

the solidity compiler will always read the length of the array during each iteration. That is,

1. if it is a storage array, this is an extra sload operation (100 additional extra gas (EIP-2929) for each iteration except for the first),

2. if it is a memory array, this is an extra mload operation (3 additional gas for each iteration except for the first),

3. if it is a calldata array, this is an extra calldataload operation (3 additional gas for each iteration except for the first)

This extra costs can be avoided by caching the array length (in stack): uint length = arr.length; for (uint i = 0; i < length; i++) { // do something that doesn't change arr.length }

proof

https://github.com/code-423n4/2022-04-jpegd/blob/e72861a9ccb707ced9015166fbded5c97c6991b6/contracts/vaults/NFTVault.sol#L181

https://github.com/code-423n4/2022-04-jpegd/blob/e72861a9ccb707ced9015166fbded5c97c6991b6/contracts/vaults/yVault/strategies/StrategyPUSDConvex.sol#L145

2 .use of != for comparison instead of > 0

impact

!= 0 costs less gas compared to > 0 for in require statements

proof

https://github.com/code-423n4/2022-04-jpegd/blob/e72861a9ccb707ced9015166fbded5c97c6991b6/contracts/vaults/NFTVault.sol#L926