Web3 & DApp Development Fundamentals · 课时

循环与 Calldata 技巧

更低成本的操作

第 3 / 4 课13 个步骤

循环与 Calldata 技巧 是 CoddyKit 上的免费 Web3 & DApp Development Fundamentals 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web3 & DApp Development Fundamentals 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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++) { }

Avoid Storage Inside Loops

Never read or write the same storage slot repeatedly inside a loop. Accumulate into a local variable and write the result once after the loop ends.

// GOOD: single storage write after the loop
uint256 total = 0;
for (uint256 i = 0; i < len; i++) {
    total += amounts[i];
}
balance = total; // one SSTORE

Unchecked Increment

Since Solidity 0.8, arithmetic has built-in overflow checks that cost extra gas. A loop counter that can never realistically overflow can be incremented inside an unchecked block.

for (uint256 i = 0; i < len;) {
    // loop body
    unchecked { ++i; }
}

Pre-increment over Post-increment

++i is marginally cheaper than i++ because post-increment must produce a temporary copy of the old value. The saving is tiny per operation but adds up across many iterations.

Prefer ++i in loop counters where the return value is unused.

for (uint256 i = 0; i < len; ++i) {
    // ++i avoids a temporary copy
}

Calldata over Memory

For external functions, declaring array and struct parameters as calldata instead of memory avoids copying the data into memory. Calldata is read-only and cheaper to access.

// Cheaper: no memory copy
function process(uint256[] calldata data) external {
    for (uint256 i = 0; i < data.length; ++i) { }
}

Shrink Calldata

Each non-zero calldata byte costs 16 gas. Smaller payloads mean cheaper transactions. Techniques include:

  • Packing multiple values into one uint256
  • Using smaller types where the ABI allows
  • Passing indices instead of full structs when the data is already on-chain

Short-Circuit Conditions

Logical operators && and || short-circuit: the second operand is only evaluated if needed. Order conditions so the cheapest or most-likely-decisive check comes first.

// Check the cheap flag before the expensive storage read
if (isEnabled && expensiveStorageCheck()) {
    // ...
}

Avoid Redundant Reads

If you access the same calldata or memory element multiple times in a loop body, cache it in a local variable. While calldata access is cheaper than storage, repeated access still adds up.

for (uint256 i = 0; i < len; ++i) {
    uint256 v = data[i]; // read once
    total += v;
    if (v > max) max = v;
}

Bound Your Loops

Unbounded loops over user-controlled arrays can exceed the block gas limit, making the function permanently uncallable (a denial-of-service risk).

Always cap iteration counts or use a pull-based pattern where users process their own entries, keeping each transaction within safe gas bounds.

require(ids.length <= 100, "too many");
for (uint256 i = 0; i < ids.length; ++i) { }

Putting It Together

An optimized loop typically: caches the length, accumulates into locals, uses calldata inputs, increments with unchecked { ++i; }, and stays bounded.

Each trick is small alone, but combined they can cut loop gas by a large fraction.

function batch(uint256[] calldata vals) external {
    uint256 len = vals.length;
    uint256 total;
    for (uint256 i = 0; i < len;) {
        total += vals[i];
        unchecked { ++i; }
    }
    sum = total;
}

Quick Check

Why is using calldata instead of memory for an external function's array parameter cheaper?

Recap

You learned loop and calldata gas tricks:

  • Cache array length before looping
  • Accumulate in locals, write storage once
  • Use unchecked { ++i; } for safe counters
  • Prefer calldata parameters and shrink payloads
  • Always bound loops to avoid gas-limit DoS

Next we measure these gains with profiling tools.

免费开始

用 AI 导师学习 Web3 & DApp Development Fundamentals — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
29
课程
105

常见问题解答

「循环与 Calldata 技巧」课时是免费的吗?

是的 — 「循环与 Calldata 技巧」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web3 & DApp Development Fundamentals 课程的其余内容,请升级到 CoddyKit PRO。 Web3 & DApp Development Fundamentals 课程共包含 4 节课。

「循环与 Calldata 技巧」这节课中我会学到什么?

更低成本的操作 你通过在浏览器中直接运行的动手代码来练习 Web3 & DApp Development Fundamentals,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web3 & DApp Development Fundamentals 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web3 & DApp Development Fundamentals 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「循环与 Calldata 技巧」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web3 & DApp Development Fundamentals 课中编写并运行代码吗?

能。每节 Web3 & DApp Development Fundamentals 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Gas 成本模型
  2. 存储优化
  3. 循环与 Calldata 技巧
  4. 测量 Gas
← 返回 Web3 & DApp Development Fundamentals