20,000 USDC
View results
Submission Details
Severity: gas

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

Summary Replacing state variable reads and writes within loops with local variable reads and writes can potentially save gas in certain situations. Let's explore how and when this gas optimization can be beneficial.

When you access or modify a state variable within a loop, each read or write operation incurs gas costs. These costs can accumulate significantly if the loop iterates a large number of times.
To optimize gas usage, you can cache the state variable in a local variable before entering the loop and perform operations on the local variable instead. Here's an example to illustrate this:
contract MyContract {
uint256 public counter;

function incrementCounter(uint256 iterations) external {
    for (uint256 i = 0; i < iterations; i++) {
        // Reading and writing the state variable within the loop
        counter++;
    }
}

}

In the above example, the function incrementCounter iterates iterations times and increments the counter state variable within the loop. Each read and write operation on the state variable incurs gas costs.

To optimize gas usage, you can cache the state variable in a local variable before entering the loop:

function incrementCounter(uint256 iterations) external {
uint256 cachedCounter = counter;

for (uint256 i = 0; i < iterations; i++) {
    // Modifying the local variable within the loop
    cachedCounter++;
}

counter = cachedCounter;

}

By caching the state variable in cachedCounter and performing operations on the local variable, you avoid repeated reads and writes to the state variable within the loop, resulting in lower gas costs.

Support

FAQs

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