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

Replace state variable reads and writes within loops with local variable reads and writes.

Reading and writing local variables is cheap, whereas reading and writing state variables that are stored in contract storage is expensive.

function badCode() external {
for(uint256 i; i < myArray.length; i++) { // state reads
myCounter++; // state reads and writes
}
}

function goodCode() external {
uint256 length = myArray.length; // one state read
uint256 local_mycounter = myCounter; // one state read
for(uint256 i; i < length; i++) { // local reads
local_mycounter++; // local reads and writes
}
myCounter = local_mycounter; // one state write
}

Recommendations

before use state var in loop first cache it in local varibel

Support

FAQs

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