Batch operations in Blockchain / Solidity - Time & Space Complexity
When working with blockchain, batch operations let us handle many tasks at once. Understanding how the time needed grows as we add more tasks is important.
We want to know: how does doing many operations together affect the time it takes?
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++) {
token.transfer(recipients[i], amount);
}
}
This code sends tokens to many addresses one after another in a loop.
- Primary operation: The for-loop that calls
token.transferfor each recipient. - How many times: Once for each 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 time grows directly with the number of recipients. Double the recipients, double the work.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of recipients.
[X] Wrong: "Batch operations always run in constant time because they are done together."
[OK] Correct: Even if done in one function, each operation inside the batch still runs one after another, so time grows with the number of operations.
Understanding how batch operations scale helps you explain efficiency clearly. This skill shows you can think about real blockchain costs and user experience.
"What if the batch function called another function that itself loops over the recipients? How would the time complexity change?"