gas

Prefer array assignment over pushing elements in for-loops

Reward

Total

19.63 USDC

Selected
6.25 USDC
4.46 USDC
4.46 USDC
4.46 USDC
Selected Submission

Prefer array assignment over pushing elements in for-loops

Severity

Gas Optimization / Informational

It is more cost-effective to directly assign tokenAddresses to s_collateralTokens.

Saving on gas based on the number of elements in tokenAddresses: (was measured without gas optimizer)

1 Element in tokenAddresses2 Elements in tokenAddresses3 Elements in tokenAddresses
gas saved-178119416

If there is only one element in tokenAddresses, this method would cost more because using one .push() is cheaper than directly assigning the array. But after the first .push(), each subsequent .push() operation would incur an additional deployment gas cost of 297 gas for each additional element, if the array is not directly assigned. Therefore, even with only two elements, it is more cost-effective to directly assign the array.

Before:

File src/DSCEngine.sol
112:    constructor(address[] memory tokenAddresses, address[] memory priceFeedAddresses, address dscAddress) {
113:        // USD Price Feeds
114:        if (tokenAddresses.length != priceFeedAddresses.length) {
115:            revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength();
116:        }
117:        // For example ETH / USD, BTC / USD, MKR / USD, etc
118:        for (uint256 i = 0; i < tokenAddresses.length; i++) {
119:            s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
120:            s_collateralTokens.push(tokenAddresses[i]); //Pushing each individual element into the array
121:        }
122:        i_dsc = DecentralizedStableCoin(dscAddress);
123:    }

After:

File src/DSCEngine.sol
112:    constructor(address[] memory tokenAddresses, address[] memory priceFeedAddresses, address dscAddress) {
113:        // USD Price Feeds
114:        if (tokenAddresses.length != priceFeedAddresses.length) {
115:            revert DSCEngine__TokenAddressesAndPriceFeedAddressesMustBeSameLength();
116:        }
117:        // For example ETH / USD, BTC / USD, MKR / USD, etc
118:        for (uint256 i = 0; i < tokenAddresses.length; i++) {
119:            s_priceFeeds[tokenAddresses[i]] = priceFeedAddresses[i];
120:        }
121:        s_collateralTokens = tokenAddresses; //Assign the array directly
122:        i_dsc = DecentralizedStableCoin(dscAddress);
123:    }

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