반복문과 Calldata 기법
더 저렴한 연산
반복문과 Calldata 기법은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 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.
AI 튜터와 함께 Web3 & DApp Development Fundamentals을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 29
- 레슨
- 105
자주 묻는 질문
“반복문과 Calldata 기법” 강의는 무료인가요?
네 — “반복문과 Calldata 기법” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“반복문과 Calldata 기법”에서 뭘 배우나요?
더 저렴한 연산 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“반복문과 Calldata 기법” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.