0
0
Blockchain / Solidityprogramming~5 mins

Gas optimization for L2 in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Gas optimization for L2
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look for loops or repeated actions that affect gas cost.

  • Primary operation: The for-loop that calls _transfer for each recipient.
  • How many times: Once for each recipient in the recipients array.
How Execution Grows With Input

As the number of recipients grows, the number of transfers grows too.

Input Size (n)Approx. Operations
1010 transfers
100100 transfers
10001000 transfers

Pattern observation: The work grows directly with the number of recipients.

Final Time Complexity

Time Complexity: O(n)

This means the gas cost increases linearly as you add more recipients.

Common Mistake

[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.

Interview Connect

Understanding how gas cost scales with batch size shows you can write efficient smart contracts that save users money.

Self-Check

"What if we replaced the for-loop with a single call that transfers to all recipients at once? How would the time complexity change?"