Assertion patterns in Blockchain / Solidity - Time & Space Complexity
When working with blockchain code, assertions help check if conditions are true during execution.
We want to see how these checks affect the time it takes for the program to run as input grows.
Analyze the time complexity of the following code snippet.
function validateTransactions(transactions) {
for (let i = 0; i < transactions.length; i++) {
assert(transactions[i].amount > 0, "Amount must be positive");
}
}
This code checks each transaction to make sure its amount is positive using an assertion.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each transaction to run an assertion check.
- How many times: Once for every transaction in the list.
As the number of transactions grows, the number of assertion checks grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 assertion checks |
| 100 | 100 assertion checks |
| 1000 | 1000 assertion 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 with the number of transactions.
[X] Wrong: "Assertions run instantly and donβt add to time as input grows."
[OK] Correct: Each assertion runs once per item, so more items mean more checks and more time.
Understanding how assertions affect time helps you write efficient blockchain code and explain your reasoning clearly.
"What if we added nested assertions inside another loop? How would the time complexity change?"