Files
nexus/wiki/concepts/GasOptimization.md
2026-05-03 05:42:12 +08:00

2.2 KiB
Raw Blame History

title, type, tags, last_updated
title type tags last_updated
GasOptimization concept
2026-05-01

Definition

Gas Optimization 是指在 EVM 智能合约开发中,通过技术手段降低合约执行和部署的 Gas 消耗,直接减少用户费用和以太坊网络的负担。由于每个区块的 Gas 上限固定,优化 Gas 消耗也是提高协议吞吐量的关键。

Core Gas Costs (EVM)

操作 Cold Access Warm Access
SLOAD读取存储 2100 gas 100 gas
SSTORE new写入新槽 20000 gas -
SSTORE update更新槽 5000 gas 2900 gas
CALL外部调用 2600 gas + 被调函数 gas 100 gas
CREATE创建合约 32000 gas -

Key Patterns

1. Storage Packing存储打包

将多个小类型打包进同一 32 字节槽,节省 SSTORE 次数:

// ✅ Good: 2 个变量共享一个槽
struct PackedData {
    uint128 amount;  // 16 bytes
    uint128 id;      // 16 bytes → 同槽
}

2. Calldata over Memory

// ✅ Good: calldata 只读,节省拷贝
function processIds(uint256[] calldata ids) external pure {}

// ❌ Bad: memory 需要拷贝到内存
function processIds(uint256[] memory ids) external pure {}

3. Custom Errors over Require Strings

// ✅ Good: 节省 ~50 gas/revert
error InsufficientBalance(uint256 requested, uint256 available);
require(balance >= amount, "Insufficient balance");

// ❌ Bad: 错误信息存储在字节码中
require(balance >= amount, "Insufficient balance for this operation");

4. Immutable over Constant运行时

uint256 public constant MAX_SUPPLY = 1_000_000;     // 编译时常量
address public immutable owner;                      // 运行时只设置一次

5. External over Public

  • External 函数:调用时参数通过 calldata 传递
  • Public 函数:需要检查是否内部调用,参数通过 memory 传递
  • 仅被内部调用 → public仅被外部调用 → external

6. Unchecked MathSafe Math

unchecked { counter++; }  // 已知 counter 不会溢出

Sources