gas

[G-01] - Use `do-while` loop instead of `for-loop` to save users gas cost.

Reward

Total

17.35 USDC

3.21 USDC
3.21 USDC
3.21 USDC
4.50 USDC
3.21 USDC
Selected Submission

[G-01] - Use do-while loop instead of for-loop to save users gas cost.

Severity

Gas Optimization / Informational

Relevant GitHub Links

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

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L353-L357

Details

do-while does not check the first condition and prevents the assembly from executing lots of opcodes needed for conditions checks and all these places are right for it because these all always execute the code inside loops on the first condition.

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

Deployment Cost

Calculation TypeBeforeAfterGas Saved
Avg1004332100427458
         // For example ETH / USD, BTC / USD, MKR / USD, etc
-        for (uint256 i = 0; i < tokenAddresses.length; i++) {
+        uint256 i;
+
+        do {
             s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
             s_collateralTokens.push(tokenAddresses[i]);
-        }
+            i++;
+        } while (i < tokenAddresses.length);
+
         i_dsc = DecentralizedStableCoin(dscAddress);

https://github.com/Cyfrin/2023-07-foundry-defi-stablecoin/blob/main/src/DSCEngine.sol#L353-L357

Calculation TypeBeforeAfterGas Saved
Avg4235642211145
         // the price, to get the USD value
-        for (uint256 i = 0; i < s_collateralTokens.length; i++) {
+        uint256 i;
+        do {
             address token = s_collateralTokens[i];
             uint256 amount = s_collateralDeposited[user][token];
             totalCollateralValueInUsd += getUsdValue(token, amount);
-        }
+            i++;
+        } while (i < s_collateralTokens.length);
+
         return totalCollateralValueInUsd;