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

`array.length` should not be retrieved in every for-loop iteration

Summary

array.length should not be retrieved in every for-loop iteration

Vulnerability Details

In the below examples related to for-loops, we can see that each time a given for-loop is executed, we have to get the array length in every for-loop iteration again and again. This will result in addictional gas spending on each iteration.

There are total of 6 instances of this problem and all of them are located in the Lender.sol contract:

File: beedle/src/Lender.sol
Lines:
233: for (uint256 i = 0; i < borrows.length; i++) {
293: for (uint256 i = 0; i < loanIds.length; i++) {
359: for (uint256 i = 0; i < loanIds.length; i++) {
438: for (uint256 i = 0; i < loanIds.length; i++) {
549: for (uint256 i = 0; i < loanIds.length; i++) {
592: for (uint256 i = 0; i < refinances.length; i++) {

Impact

This problem will cause additional gas consumption for every iteration of the for-loop due to the fact that array.length is not cached. The value of array.length would have to be recalculated at the beginning of each loop iteration, leading to a higher gas cost.

Tools Used

Manual Review

Recommendations

Instead of re-evaluating the array.length value each time an interation of the loop is performed, it is better to declare a variable before the for-loop declaration, where the length of the array would be cached. This approach will save gas due to the fact that it won't be necessary to calculate the length of the array each time.

Here is code example:

uint256 arrayLength = 0;
for (uint256 i = 0; i < arrayLength; i++) {

Support

FAQs

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

Give us feedback!