Require, assert, and revert in Blockchain / Solidity - Time & Space Complexity
When using require, assert, and revert in blockchain code, it's important to know how they affect the program's speed as input grows.
We want to see how these checks impact the number of steps the program takes.
Analyze the time complexity of the following code snippet.
function transfer(address to, uint amount) public {
require(balance[msg.sender] >= amount, "Insufficient balance");
balance[msg.sender] -= amount;
balance[to] += amount;
assert(balance[msg.sender] >= 0);
if(amount > 1000) {
revert("Amount too large");
}
}
This code checks conditions before and after transferring tokens, stopping execution if something is wrong.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: There are no loops or repeated traversals here; the checks happen once per function call.
- How many times: Each require, assert, and revert runs only once each time the function is called.
Since the checks run once per call, the number of steps stays about the same no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 checks and updates |
| 100 | 5 checks and updates |
| 1000 | 5 checks and updates |
Pattern observation: The work does not increase with input size; it stays constant.
Time Complexity: O(1)
This means the checks take the same amount of time no matter how big the input is.
[X] Wrong: "Require, assert, and revert slow down the program more as input grows."
[OK] Correct: These checks run once per call and do not loop over input, so their cost stays the same regardless of input size.
Understanding how these checks affect performance helps you write safe and efficient blockchain code, a skill valued in real projects.
"What if the require statement was inside a loop over an array of inputs? How would the time complexity change?"