RareSkills Solidity Interview Question #33 Answered: How do you write a gas-efficient for loop in Solidity?

Faybian Byrd
Coinmonks
3 min readMar 1, 2024

--

This series will provide answers to the list of Solidity interview questions that were published by RareSkills..

Question #33 (Medium): How do you write a gas-efficient for loop in Solidity?

Answer: To write a gas-efficient for loop in Solidity, you should cache all variables that read from storage, to avoid multiple storage reads for the same variable. Also, gas can be saved by updating the iterator in an unchecked block, which avoids the compiler’s overflow checks. Another technique is to increment the iterator using a prefix operator (for example, ++i) instead of a postfix operator (i++).

Demonstration:

// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.24;

contract EfficientLoop {
uint256 loopLimit = 10;

function loop() external view {
uint256 cachedLoopLimit = loopLimit;

for (uint256 i = 0; i < cachedLoopLimit;) {
// ...

unchecked {
++i;
}
}
}
}

Further Discussion:

Starting in Solidity 0.8.0, the compiler provides overflow and underflow protection by checking if math operations would result in an overflow or underflow and if so, reverts the transaction. These checks require extra opcodes to be executed, resulting in more gas to be consumed. It is possible to tell the compiler to omit these checks by wrapping math operations in unchecked blocks. This ultimately results in less gas. Since it is unlikely that an iterator would cause an overflow, it might be more efficient to forego the overflow check for the incrementation.

Also, a prefix operator can be more efficient than a postfix operator because ++i increments the original value and returns the new value, resulting in only one value being stored on the stack (the new value), whereas, i++ creates a copy of the original value, increments the original, and then returns the copied value, requiring 2 values to be stored on the stack. Since the prefix operator does not copy the value, it performs less opcodes than the postfix operator.

More gas-optimization tips and tricks can be found in The RareSkills Book of Solidity Gas Optimization: 80+ Tips.

Connect with me:

Latest articles:

Disclosure: Some content may have been generated with the help of artificial intelligence.

--

--

Faybian Byrd
Coinmonks

Senior Software Engineer, Full Stack/Frontend @Synapse Labs | Graduate - Advanced Solidity Bootcamp @ RareSkills. | Certified Solidity Developer (CSD)