가스 측정하기
프로파일링 도구
가스 측정하기은(는) CoddyKit의 무료 Web3 & DApp Development Fundamentals 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web3 & DApp Development Fundamentals 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Measure, Don't Guess
Gas optimization without measurement is guesswork. The compiler, opcode costs, and access patterns interact in non-obvious ways, so an intuitive change can sometimes make things worse.
Always profile before and after. A change that does not reduce measured gas is not an optimization, no matter how clever it looks.
Forge Gas Reports
Foundry's forge test --gas-report prints a per-function table of min, average, median, and max gas usage across all your tests. It is the fastest way to spot expensive functions.
$ forge test --gas-report
| Function | min | avg | median | max | # calls |
| transfer | 28012 | 34521 | 34521 | 51012 | 12 |
| approve | 24300 | 24300 | 24300 | 24300 | 5 |Gas Snapshots
forge snapshot writes the gas cost of every test to a .gas-snapshot file. Commit it to version control, then run forge snapshot --diff to see exactly how a change affected gas.
This turns gas regressions into reviewable diffs in pull requests.
$ forge snapshot
$ forge snapshot --diff
testTransfer() (gas: -1240 (-3.6%))
testMint() (gas: +85 (+0.2%))Measuring in Tests
For fine-grained measurement, read gasleft() before and after a call inside a test. The difference is the gas consumed by that block of code.
uint256 before = gasleft();
target.doWork();
uint256 used = before - gasleft();
emit log_named_uint("gas used", used);Verbose Traces
Running tests with -vvvv shows a full execution trace including the gas cost of each external call and opcode group. This reveals where gas is spent, not just the total.
$ forge test --match-test testTransfer -vvvv
[34521] Token::transfer(bob, 100)
emit Transfer(from: alice, to: bob, value: 100)
return: trueThe Optimizer Setting
The Solidity optimizer changes runtime and deployment gas. The runs parameter is a hint about how often functions are called.
- Low
runs(e.g. 1) optimizes for cheap deployment - High
runs(e.g. 10000) optimizes for cheap repeated calls
Set it in foundry.toml and always measure with the optimizer enabled, since it reflects production behavior.
# foundry.toml
[profile.default]
optimizer = true
optimizer_runs = 10000Comparing Implementations
To compare two approaches, write a test that exercises each under identical conditions and inspect the gas report side by side.
Keep inputs the same and isolate the change to one variable, otherwise you cannot attribute the gas difference to the optimization you made.
function testNaive() public { c.sumNaive(data); }
function testOptimized() public { c.sumOptimized(data); }
// compare both rows in --gas-reportBeware Warm vs Cold Skew
Gas reports can mislead because the first access in a test is cold and later ones are warm. A function called once in setup may show a higher cold cost than the same function later.
Look at min, median, and max columns together rather than a single average, and design tests that reflect real-world access patterns.
Etherscan and Real Receipts
On-chain transaction receipts report the actual gasUsed. Etherscan and block explorers display this for every transaction, letting you validate your local measurements against mainnet reality.
The eth_estimateGas RPC method gives a pre-flight estimate, though it adds a safety margin and may differ from the real execution cost.
CI Gas Regression Gates
Wire forge snapshot --check into continuous integration. It fails the build if any test's gas exceeds the committed snapshot beyond a tolerance.
This prevents accidental gas regressions from slipping into production and makes gas a first-class quality metric.
$ forge snapshot --check
# exits non-zero if gas increased vs committed snapshotA Measurement Workflow
A solid gas workflow:
- Write tests covering the hot paths
- Record a baseline with
forge snapshot - Make one optimization at a time
- Run
forge snapshot --diffto confirm the gain - Gate regressions in CI with
--check
Discipline beats cleverness.
Quick Check
Which Foundry command produces a per-function table of min, average, and max gas usage?
Recap
You learned to measure gas:
forge test --gas-reportfor per-function tablesforge snapshot --diffto track changesgasleft()for fine-grained measurement- Verbose traces reveal where gas goes
- Gate regressions in CI with
--check
This completes the Gas Optimization course. Next: the Foundry toolkit in depth.
AI 튜터와 함께 Web3 & DApp Development Fundamentals을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 29
- 레슨
- 105
자주 묻는 질문
“가스 측정하기” 강의는 무료인가요?
네 — “가스 측정하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web3 & DApp Development Fundamentals 강의 전체를 잠금 해제할 수 있습니다. Web3 & DApp Development Fundamentals 강의에는 총 4개의 강의가 포함되어 있습니다.
“가스 측정하기”에서 뭘 배우나요?
프로파일링 도구 브라우저에서 직접 실행하는 실습 코드로 Web3 & DApp Development Fundamentals을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web3 & DApp Development Fundamentals을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web3 & DApp Development Fundamentals은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.
“가스 측정하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web3 & DApp Development Fundamentals 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web3 & DApp Development Fundamentals 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.