問題一覧に戻る
上級ガス最適化
問題84: ループ最適化
Solidityのループ最適化を学習 - ガス制限管理とバッチ処理。大きなループはブロックガス制限を超え、トランザクション失敗を引き起こします。配列長のキャッシュは余分なSLOAD操作を防止。バッチ処理は大きな操作を管理可能なチャンクに分割。ループ最適化の理解は、大量データセット、ユーザーリスト、一括操作をガス制限にぶつからずに処理するために不可欠です。
pragma solidity ^0.8.0;
contract LoopOptimization {
uint256[] public items;
mapping(address => bool) public processed;
// 非効率:各反復で長さを再計算
function badLoop(address[] memory users) public {
for (uint256 i = 0; i < users.; i++) {
// 高価な操作
processed[users[i]] = true;
}
}
// 最適化:ループ前に長さをキャッシュ
function optimizedLoop(address[] memory users) public {
uint256 length = users.;
for (uint256 i = 0; i < ; i++) {
processed[users[i]] = true;
}
}
// 大量データセットのバッチ処理
function batchProcess(
address[] calldata users,
uint256 startIndex,
uint256 batchSize
) public {
uint256 endIndex = startIndex + ;
// ガス制限を尊重
if (endIndex > users.length) {
endIndex = users.;
}
for (uint256 i = startIndex; i < ; i++) {
processed[users[i]] = true;
}
}
}