Challenge 21
Loop optimization
GasGas optimization
Challenge
Review the loop and identify the gas-heavy pattern that could be avoided in a large array operation.
Starter code
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract LoopStudy {
uint256[] public values;
function total() public view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < values.length; i++) {
sum += values[i];
}
return sum;
}
}Show hint
Look for repeated external costs or unnecessary operations inside the loop.