Cache loop length in stack instead of reading from memory every iteration. Replace for (...; i < arr.length; ...) { ... } with uint cachedLength = arr.length; for (...; i < cachedLength; ...) { ... }.
Use ++i for increments if the resulting value is not immediately needed. It costs less gas compared to i++ or i+=1 - as no temporary variable needs to exist in order to return the unincremented value.
Use unchecked arithmetic in counters, Solidity 0.8.x checks for overflow/underflow by default, which is not needed in this case. Replace for (...; ... ; ++i) { ... } with for (...; ...; ) { ... unchecked { ++i; } }
Gas optimizations
When checking if
uint
are equal to zero, usinguint != 0
is cheaper thanuint > 0
. Applicable in lines 293, 327, 351, 427, 498, 598, 599Loops (lines 556, 594, 611, 627, 637, 647, 658, 670, 728, 742)
memory
every iteration. Replacefor (...; i < arr.length; ...) { ... }
withuint cachedLength = arr.length; for (...; i < cachedLength; ...) { ... }
.++i
for increments if the resulting value is not immediately needed. It costs less gas compared toi++
ori+=1
- as no temporary variable needs to exist in order to return the unincremented value.for (...; ... ; ++i) { ... }
withfor (...; ...; ) { ... unchecked { ++i; } }