Cyfrin / 2023-07-foundry-defi-stablecoin

37 stars 32 forks source link

Use unchecked on iterator for gas savings #1120

Open codehawks-bot opened 1 year ago

codehawks-bot commented 1 year ago

Use unchecked on iterator for gas savings

Severity

Gas Optimization / Informational

Relevant GitHub Links

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/d1c5501aa79320ca0aeaa73f47f0dbc88c7b77e2/src/DSCEngine.sol#L118-L121

Summary

Can save gas if unchecked and ++i are used.

Vulnerability Details

++i/i++ Should Be unchecked{++i}/unchecked{i++} When It Is Not Possible For Them To Overflow

Impact

++i costs less gas than i++, and will cost even less when put in an unchecked block.

Tools Used

Manual review

Recommendations

Change this:

        for (uint256 i = 0; i < tokenAddresses.length; i++) {
            s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
            s_collateralTokens.push(tokenAddresses[i]);
        }

To this:

        for (uint256 i = 0; i < tokenAddresses.length;) {
            s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
            s_collateralTokens.push(tokenAddresses[i]);
            unchecked {
              ++i;
            }
        }