Tricks mit Schleifen und Calldata
Günstigere Operationen
Tricks mit Schleifen und Calldata ist eine kostenlose Web3 & DApp Development Fundamentals-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Web3 & DApp Development Fundamentals-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Web3 & DApp Development Fundamentals-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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 SSTOREUnchecked 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
calldataparameters and shrink payloads - Always bound loops to avoid gas-limit DoS
Next we measure these gains with profiling tools.
Häufig gestellte Fragen
Ist die Lektion „Tricks mit Schleifen und Calldata“ kostenlos?
Ja — der vollständige Text von „Tricks mit Schleifen und Calldata“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Web3 & DApp Development Fundamentals-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Web3 & DApp Development Fundamentals-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Tricks mit Schleifen und Calldata“?
Günstigere Operationen Du übst Web3 & DApp Development Fundamentals mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Web3 & DApp Development Fundamentals zu starten?
Keine Vorkenntnisse erforderlich. Web3 & DApp Development Fundamentals auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „Tricks mit Schleifen und Calldata“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Web3 & DApp Development Fundamentals-Lektion Code schreiben und ausführen?
Ja. Jede Web3 & DApp Development Fundamentals-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Gas-Kostenmodell
- Storage-Optimierung
- Tricks mit Schleifen und Calldata
- Gas messen