Why gas efficiency saves money in Blockchain / Solidity - Performance Analysis
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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that calls
transferfor each recipient. - How many times: Once for every address in the
recipientslist.
As the number of recipients grows, the number of transfers grows the same way.
| 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. Double the recipients, double the work.
Time Complexity: O(n)
This means the cost grows in a straight line with the number of recipients. More recipients mean more gas spent.
[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.
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.
"What if we replaced the loop with a single batch transfer call that handles all recipients at once? How would the time complexity change?"