F-2023-0012·gas-optimization

Cache array length outside of loop saves gas

TL;DR

Reading array.length on every loop iteration costs an extra SLOAD or MLOAD per pass; caching it once before the loop saves gas at scale.

Severity
INFO
Impact
LOW
Likelihood
LOW
Method
MManual review
CAT.
Complexity
LOW
Exploitability
LOW
02Section · Description

Description

If not cached, the Solidity compiler will always read the length of the array during each iteration.

That is, if it is a storage array, this is an extra SLOAD operation (100 additional extra gas for each iteration except for the first) and if it is a memory array, this is an extra MLOAD operation (3 additional gas for each iteration except for the first).

This scenario is repeated many times throughout the code:

solidity
for (uint256 i = 0; i < ids.length; ++i) {}
03Section · Recommendation

Recommendation

Consider extracting that to a local variable outside the loop:

solidity
uint256 len = ids.length;
for (uint256 i = 0; i < len; ++i) {}
F-2023-0012

oog
zealynx

Smart Contract Security Digest

Monthly exploit breakdowns, audit checklists, and DeFi security research — straight to your inbox

© 2026 Zealynx