Simple smart contract that calculates the sum of an array, and then shows how to optimize it for gas efficiency in three major steps. This is a practical example of how real-world Ethereum developers reduce gas costs.
Letβs break it down:
pragma solidity ^0.8.0;
contract SumContract {
uint256[] public arr = [1, 2, 3, 4, 5];
uint256 public sum;
function calculateSum() public {
for (uint256 i = 0; i < arr.length; i++) {
sum += arr[i]; // β Problem: Modifying state in a loop
}
}
}
π΄ Issues with this code:
sum) inside a loop β very expensive in gasarr) β slow and costlysum += arr[i]; // Writes to storage every iteration!
sum is a state variable β stored on blockchainUse a local variable in memory to accumulate the sum, then assign it to the state variable once at the end.