0Pricing
Web3 & DApp Development Fundamentals · Lesson

Loop and Calldata Tricks

Cheaper operations.

Loops Multiply Cost

Loops are dangerous for gas because every operation inside runs once per iteration. A single expensive call inside a loop can blow your gas budget or hit the block gas limit.

The goal is to push as much work as possible outside the loop and make each iteration as cheap as possible.

Cache the Length

Reading array.length on a storage array costs an SLOAD each time the loop condition is checked. Cache the length in a local variable before the loop.

// BAD: SLOAD on every iteration
for (uint256 i = 0; i < items.length; i++) { }

// GOOD: one SLOAD
uint256 len = items.length;
for (uint256 i = 0; i < len; i++) { }

All lessons in this course

  1. Gas Cost Model
  2. Storage Optimization
  3. Loop and Calldata Tricks
  4. Measuring Gas
← Back to Web3 & DApp Development Fundamentals