Why logic controls execution in Blockchain / Solidity - Performance Analysis
In blockchain programming, the logic you write decides how many steps your code takes.
We want to see how this logic affects the time it takes to run as input grows.
Analyze the time complexity of the following code snippet.
function processTransactions(transactions) {
for (let i = 0; i < transactions.length; i++) {
if (transactions[i].amount > 1000) {
validateTransaction(transactions[i]);
}
}
}
function validateTransaction(tx) {
// some validation logic here
}
This code checks each transaction and only validates those over 1000 units.
- Primary operation: Looping through all transactions once.
- How many times: Once for each transaction in the list.
As the number of transactions grows, the code checks each one once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the number of transactions.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Since only some transactions are validated, the code runs faster than checking all."
[OK] Correct: The loop still checks every transaction, so the time grows with all transactions, not just the validated ones.
Understanding how your logic controls execution helps you write efficient blockchain code and explain it clearly in conversations.
"What if we added a nested loop to validate transactions against a list of rules? How would the time complexity change?"