code-423n4 / 2021-10-union-findings

0 stars 0 forks source link

.length in a loop #92

Open code423n4 opened 3 years ago

code423n4 commented 3 years ago

Handle

pauliax

Vulnerability details

Impact

.length in a loop can be extracted into a variable and used where necessary to reduce the number of storage reads. An example where this could be applied: for (uint256 i = 0; i < moneyMarkets.length; i++) Solution: uint moneyMarketsLength = moneyMarkets.length; for (uint256 i = 0; i < moneyMarketsLength; i++) Cache the length of the array and use this local variable when iterating over the storage array.

GalloDaSballo commented 3 years ago

Agree with the finding, the value moneyMarkets.length is being read on each loop to verify the termination clause, since moneyMarkets is a variable in storage, you are paying 100 gas (SSLOAD_COLD - COLD-READ) every time you run the loop

You can't avoid reading from storage once, but each subsequent read can be done via a supporting memory variable, this will cost 3 extra gas for storing, and just 3 gas for each time the value is read.

Effectively bringing 94 extra gas in the worst case and 97 extra gas for each round of the loop

In terms of gas, savings, beside deployment costs, minimizing storage reads is one of the best places to start, and this seems to be great advice to start