今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Gas Optimization That Doesn't Break Security: Storage, Calldata, and the Traps

Pavel Espitia 2026年06月18日 23:15 3 次阅读 来源:Dev.to

Gas optimization is satisfying. You shave a few thousand gas off a function and feel clever. But some optimizations trade away safety in ways that are not obvious, and I have seen "optimized" contracts that introduced vulnerabilities. Here are the gas wins that are genuinely free, the ones that cost you safety, and how to tell the difference. Where gas actually goes Before optimizing, know what is expensive. Storage operations dominate. Writing a fresh storage slot ( SSTORE from zero to non-zero) costs a lot; reading storage ( SLOAD ) is cheaper but still meaningful; computation in memory is cheap by comparison. So the highest-leverage optimizations are about touching storage less. Free win 1: cache storage reads in memory If you read the same storage variable multiple times in a function, each read is an SLOAD . Read it once into a local variable instead: // WASTEFUL: reads storage `total` three times function distribute() external { require(total > 0, "empty"); uint256 share = total / count; emit Distributed(total); } // OPTIMIZED: one SLOAD, two memory reads function distribute() external { uint256 _total = total; // single storage read require(_total > 0, "empty"); uint256 share = _total / count; emit Distributed(_total); } This is free in the sense that it changes nothing about correctness. The value is identical; you just read it once. Pure win. Free win 2: calldata instead of memory for read-only arrays For external function arguments you only read (never modify), calldata is cheaper than memory because it skips the copy: // memory copies the whole array into memory function process(uint256[] memory ids) external { ... } // calldata reads directly from the transaction data, no copy function process(uint256[] calldata ids) external { ... } Again, free. If you do not mutate the array, calldata is strictly better. Free win 3: storage packing Solidity packs multiple variables into one 32-byte slot if they fit and are adjacent. Order your storage variables so smal

本文内容来源于互联网,版权归原作者所有
查看原文