Using Prefix Operators Costs Less Gas Than Postfix Operators in Loops
Description
In Solidity, there are two ways to increment a variable within a loop: i++ and ++i. The difference between them is that i++ is a post-increment operator, which increments the value of i after the expression has been evaluated, while ++i is a pre-increment operator, which increments the value of i before the expression has been evaluated.
When using these operators in a loop, it is more gas-efficient to use ++i instead of i++. The reason is that the i++ operator requires an additional SSTORE operation to store the updated value of i, which consumes more gas.
Here are some example scenarios where this optimization can be applied:
// Example 1
for (uint256 i = 0; i < n; i++) {
// do something
}
// Example 2
uint256 i = 0;
while (i < n) {
// do something
i++;
}
// Example 3
uint256 i = 0;
do {
// do something
i++;
} while (i < n);
Example Code
To illustrate the difference in gas costs between i++ and ++i, consider the following example contract:
contract GasTest {
function preIncrement(uint256 n) public {
for (uint256 i = 0; i < n; ++i) {
// do something
}
}
function postIncrement(uint256 n) public {
for (uint256 i = 0; i < n; i++) {
// do something
}
}
}
When we deploy this contract and call the preIncrement and postIncrement functions with a large value of n, we can see that using ++i consumes less gas than using i++.
Recommendation
It is recommended to use ++i instead of i++ to increment the value of a uint variable within a loop. This is not applicable outside of loops.