Skip to main content

Load State Variables To Memory

Description

In Solidity, reading values from storage can be a costly operation, especially if the same value is accessed multiple times within the same function. To avoid unnecessary gas costs, it is recommended to load frequently accessed state variables into local memory variables.

Example Code

Consider the following contract code:


contract MyContract {
uint256 public value;

function doSomething() public {
uint256 x = 1;
for (uint256 i = 0; i < 100000; i++) {
x += value; // read value from storage multiple times
}
}
}

In this example, the value state variable is accessed multiple times within the for loop. To optimize this code, we can load the value variable into a local memory variable before the loop:

pragma solidity ^0.8.0;

contract MyContract {
uint256 public value;

function doSomething() public {
uint256 x = 1;
uint256 val = value; // load value into local memory variable
for (uint256 i = 0; i < 100000; i++) {
x += val; // access value from memory
}
}
}

Recommendation

To optimize gas usage, load frequently accessed state variables into local memory variables when they are used multiple times within the same function. However, be mindful of the available memory on the Ethereum virtual machine and avoid overloading memory usage.