Skip to main content

Cache State Variables

Description

In Solidity, it is common to use state variables to store values that are used throughout a contract's functions. However, accessing state variables multiple times within a function can consume unnecessary gas. To optimize this, you can cache state variables in local variables before using them multiple times in a function.

Example Code

Consider the following example:

function someFunction(uint256 x) public {
if (block.timestamp > pool.lastTimestamp) {
if(pool.someVar > 0){
pool.someVar2 *= pool.someVar;
}
}
}

To optimize this, we can cache the value of pool.someVar in a local variable before using it:

function someFunction(uint256 x) public {
if (block.timestamp > pool.lastTimestamp) {
uint256 someVar = pool.someVar;
if(someVar > 0){
pool.someVar2 *= someVar;
}
}
}

Recommendation

To optimize gas usage in Solidity functions that use state variables, consider caching the values of state variables in local variables before using them multiple times in a function. This can save gas by avoiding the extra cost of accessing the state variable multiple times. However, it's important to ensure that the cached value is still up-to-date when it is used in the function.