0
0
Blockchain / Solidityprogramming~5 mins

Why gas efficiency saves money in Blockchain / Solidity - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why gas efficiency saves money
O(n)
Understanding Time Complexity

When working with blockchain, every operation costs gas, which means money. Understanding how the number of operations grows helps us see why saving gas is important.

We want to know how the cost changes as the work done by a smart contract increases.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function batchTransfer(address[] memory recipients, uint256 amount) public {
  for (uint i = 0; i < recipients.length; i++) {
    transfer(recipients[i], amount);
  }
}
    

This function sends tokens to many addresses by looping through each recipient and transferring tokens.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As the number of recipients grows, the number of transfers grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the cost grows in a straight line with the number of recipients. More recipients mean more gas spent.

Common Mistake

[X] Wrong: "Adding more recipients won't increase gas cost much because transfers are simple."

[OK] Correct: Each transfer uses gas, so more recipients mean more transfers and more gas. The cost adds up directly.

Interview Connect

Understanding how gas cost grows with input size shows you can write smart contracts that save money. This skill helps you build better blockchain apps and impress interviewers with practical knowledge.

Self-Check

"What if we replaced the loop with a single batch transfer call that handles all recipients at once? How would the time complexity change?"