示例一:变量缓存
原代码每次循环都读取 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% 以上下降。