15,000 USDC
View results
Submission Details
Severity: gas
Valid

Prefer array assignment over pushing elements in for-loops

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 tokenAddresses 2 Elements in tokenAddresses 3 Elements in tokenAddresses
gas saved -178 119 416

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

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.