Skip to main content

Event Emitting for State Variables and Using State Variables in For Loops

Description

In Solidity, it is possible to emit events to log information about contract state changes. However, emitting events for state variables can be gas-inefficient, as it will result in the duplication of data on the blockchain. Similarly, using state variables in for loops can also be gas-inefficient, as the cost of accessing storage in loops can quickly add up, resulting in higher gas costs.

Example Code

Here's an example of a Solidity function that makes an unnecessary state change:

contract Example {
uint256 global_test;
uint256 global_var;

event SomeEvent(uint256 indexed test);

function example(uint256 test) public {
global_test = test;
for(uint256 i; i < global_var; ++i) { // wrong way
// do something
}
emit SomeEvent(global_test); // wrong way
}
}

Recommendation

To avoid gas inefficiencies associated with event emitting for state variables and using state variables in for loops, it is recommended to instead pass variables as function arguments and use local variables in loops. This can help reduce the amount of storage accessed and data duplicated on the blockchain, resulting in lower gas costs.

contract Example {
uint256 global_test;
uint256 global_var;

event SomeEvent(uint256 indexed test);

function example(uint256 test) public {
global_test = test;
uint256 x = global_var; //correct way
for(uint256 i; i < x; ++i) { //correct way
// do something
}
emit SomeEvent(test); // correct way
}
}