for (uint256 i = 0; i < arr.length; i++) {
sum += arr[i];
}
arr.length (a storage or memory load every iteration)Optimized Loop
uint256 len = arr.length;// this is a must
for (uint256 i; i < len;) {
sum += arr[i];
unchecked { ++i; }
}
sload/mload costs (~100 gas per storage read).unchecked to skip overflow checks (safe if bounds known). unchecked saves ~30–40 gas per iteration.++i instead of i++ (slightly cheaper pre-increment). Using ++i saves ~5 gas per loop.uint80, bool, address) into one 256-bit slot to reduce storage writes.calldata instead of memory for Read-Only ParametersFor external functions, calldata avoids copying to memory, saving significant gas, especially for arrays.
storage is expensive (~100 gas per access). When a state variable is accessed multiple times within a function, each read charges gas—even for “warm” accesses (i.e. a slot you've already touched).uint256 public number;
function bad() public view returns (uint256) {
require(number < 10); // 1st read
return number * 2; // 2nd read
}
function good() public view returns (uint256) {
uint256 _num = number; // 1st and only storage read
require(_num < 10);
return _num * 2;
}
calldata vs memory