For and while loops in Blockchain / Solidity - Time & Space Complexity
When we use loops in blockchain code, the time it takes to run depends on how many times the loop repeats.
We want to know how the running time grows as the number of loop steps increases.
Analyze the time complexity of the following code snippet.
function processTransactions(transactions) {
for (let i = 0; i < transactions.length; i++) {
while (transactions[i].needsProcessing) {
process(transactions[i]);
transactions[i].needsProcessing = false;
}
}
}
This code goes through a list of transactions and processes each one if it needs processing.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer
forloop runs once for each transaction. - Secondary operation: The inner
whileloop runs until the current transaction is processed, usually once per transaction. - Dominant operation: The
forloop over all transactions dominates because it scales with the number of transactions.
As the number of transactions grows, the total steps grow roughly the same amount.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times processing steps |
| 100 | About 100 times processing steps |
| 1000 | About 1000 times processing steps |
Pattern observation: The work grows directly with the number of transactions.
Time Complexity: O(n)
This means if you double the number of transactions, the time to process roughly doubles.
[X] Wrong: "The inner while loop makes this code run much slower, like squared time."
[OK] Correct: The inner loop usually runs only once per transaction, so it does not multiply the total steps by the number of transactions.
Understanding how loops affect time helps you explain your code clearly and shows you can think about efficiency in blockchain programs.
"What if the inner while loop could run multiple times per transaction? How would the time complexity change?"