b biangogo.com
Gas优化代码示例

Gas优化代码示例:六个可直接复用的 Solidity 节流片段

Talk is cheap,show me the code。本文给出六段经过实战验证的 Gas 优化代码示例,附上前后对比,可直接搬到你的项目。

b
biangogo.com 编辑部
1378 字· 约 3 分钟阅读· 2026-05-24T06:12:20.351569+00:00
Gas优化代码示例 - Gas优化代码示例:六个可直接复用的 Solidity 节流片段
关于「Gas优化代码示例」的视觉延伸

示例一:变量缓存

原代码每次循环都读取 storage:

for (uint256 i = 0; i < users.length; i++) {
    totalLocked += userLocked[users[i]];
}

优化后:

uint256 _total = totalLocked;
uint256 len = users.length;
for (uint256 i; i < len; ) {
    _total += userLocked[users[i]];
    unchecked { ++i; }
}
totalLocked = _total;

收益:循环越长收益越大,Binance 智能链常见 30% 以上下降。

示例二:storage 槽合并