President Elector

First Flight #24
Beginner FriendlyFoundry
100 EXP
View results
Submission Details
Severity: low
Invalid

Storage Variables in a Loop Should Be Cached

Summary

Accessing storage variables within a loop is gas-inefficient because each access involves a read operation from storage. Reading from storage repeatedly can significantly increase the gas costs compared to reading from memory. To improve efficiency, storage variables should be cached in a local variable when used multiple times within a loop.

Vulnerability Details

Impact

Excessive storage reads can lead to higher gas costs, especially in loops, and can make the contract less efficient.

Tools Used

Manual review

Recommendations

Cache the storage variable in a local memory variable before entering the loop. This approach reduces the number of storage reads and lowers gas costs.

+ uint256 votersLength = VOTERS.length;
+ for (uint256 i = 0; i < votersLength; i++) {
- for (uint256 i = 0; i < VOTERS.length; i++) {
address[] memory orderedCandidates = s_rankings[VOTERS[i]][
s_voteNumber
];
+ uint256 candidatesLength = orderedCandidates.length;
+ for (uint256 j = 0; j < candidatesLength; j++) {
- for (uint256 j = 0; j < orderedCandidates.length; j++) {
if (!_isInArray(s_candidateList, orderedCandidates[j])) {
s_candidateList.push(orderedCandidates[j]);
}
}
}
Updates

Lead Judging Commences

inallhonesty Lead Judge 12 months ago
Submission Judgement Published
Invalidated
Reason: Non-acceptable severity

Support

FAQs

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