code-423n4 / 2021-12-perennial-findings

0 stars 0 forks source link

Cache array length in for loops can save gas #31

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

WatchPug

Vulnerability details

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Instances include:

https://github.com/code-423n4/2021-12-perennial/blob/fd7c38823833a51ae0c6ae3856a3d93a7309c0e4/protocol/contracts/incentivizer/Incentivizer.sol#L232-L242

function claimFee(Token18[] calldata tokens) notPaused external {
    for(uint256 i; i < tokens.length; i++) {
        Token18 token = tokens[i];
        UFixed18 amount = fees[token];

        fees[token] = UFixed18Lib.ZERO;
        tokens[i].push(factory().treasury(), amount);

        emit FeeClaim(token, amount);
    }
}
GalloDaSballo commented 2 years ago

Finding is valid, I appreciate that the warden explained the logic behind the gas savings.