code-423n4 / 2021-09-defiprotocol-findings

1 stars 0 forks source link

Accessing the length of the array in every iteration is more gas expensive #208

Closed code423n4 closed 2 years ago

code423n4 commented 2 years ago

Handle

pauliax

Vulnerability details

Impact

There are loops that iterate over storage arrays. Accessing the length of the array in every iteration is more expensive, so you should cache it and use this local variable when iterating over the storage array.

Recommended Mitigation Steps

Example: uint bProposalWightsLength = bProposal.weights.length; for (uint256 i = 0; i < bProposalWightsLength; i++)

GalloDaSballo commented 2 years ago

Agree with the finding, as a general rule you always want to cache storage values in memory if they are read more than once. Additionally, caching .length saves an extra math operation as the length is stored in a specific storage location that has to be re-calculated every loop

GalloDaSballo commented 2 years ago

Duplicate of #230