An array's length should be cached to save gas in for-loops #194
Labels
bug
Something isn't working
duplicate
This issue or pull request already exists
G (Gas Optimization)
resolved
Finding has been patched by sponsor (sponsor pls link to PR containing fix)
sponsor confirmed
Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
Handle
Dravee
Vulnerability details
Impact
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.
Proof of Concept
Tools Used
VS Code
Recommended Mitigation Steps
Store the array's length in a variable before the for-loop, and use it instead. As an example, it's already done here: https://github.com/code-423n4/2021-12-nftx/blob/main/nftx-protocol-v2/contracts/solidity/NFTXVaultUpgradeable.sol#L362-L364
The text was updated successfully, but these errors were encountered: