Using for directive in Blockchain / Solidity - Time & Space Complexity
When we use a for directive in blockchain code, it usually means repeating some steps for many items. Understanding how long this takes helps us write faster programs.
We want to know: how does the time to run grow when we have more items to process?
Analyze the time complexity of the following code snippet.
for (uint i = 0; i < transactions.length; i++) {
processTransaction(transactions[i]);
}
This code goes through each transaction in a list and processes it one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that runsprocessTransactionon each item. - How many times: Exactly once for each transaction in the list.
As the number of transactions grows, the total steps grow in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times processing |
| 100 | 100 times processing |
| 1000 | 1000 times processing |
Pattern observation: If you double the number of transactions, the work doubles too.
Time Complexity: O(n)
This means the time to finish grows directly with the number of transactions.
[X] Wrong: "The loop runs only once no matter how many transactions there are."
[OK] Correct: The loop actually runs once for each transaction, so more transactions mean more work.
Knowing how loops affect time helps you explain your code clearly and shows you understand how programs grow with data size. This skill is useful in many blockchain tasks.
"What if we nested another for loop inside this one to process pairs of transactions? How would the time complexity change?"