Gas optimization for L2 in Blockchain / Solidity - Time & Space Complexity
When working with Layer 2 (L2) blockchain solutions, gas optimization helps reduce transaction costs.
We want to understand how the cost of operations grows as we handle more data or users.
Analyze the time complexity of the following L2 gas optimization snippet.
function batchTransfer(address[] memory recipients, uint256 amount) public {
for (uint i = 0; i < recipients.length; i++) {
_transfer(msg.sender, recipients[i], amount);
}
}
This code sends tokens to many recipients in one batch to save gas compared to individual transfers.
Look for loops or repeated actions that affect gas cost.
- Primary operation: The for-loop that calls
_transferfor each recipient. - How many times: Once for each recipient in the
recipientsarray.
As the number of recipients grows, the number of transfers grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 transfers |
| 100 | 100 transfers |
| 1000 | 1000 transfers |
Pattern observation: The work grows directly with the number of recipients.
Time Complexity: O(n)
This means the gas cost increases linearly as you add more recipients.
[X] Wrong: "Batching transfers makes gas cost constant no matter how many recipients there are."
[OK] Correct: Each transfer still uses gas, so total cost grows with the number of recipients, even if batching saves some overhead.
Understanding how gas cost scales with batch size shows you can write efficient smart contracts that save users money.
"What if we replaced the for-loop with a single call that transfers to all recipients at once? How would the time complexity change?"