0
0
Blockchain / Solidityprogramming~5 mins

Require, assert, and revert in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Require, assert, and revert
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
105 checks and updates
1005 checks and updates
10005 checks and updates

Pattern observation: The work does not increase with input size; it stays constant.

Final Time Complexity

Time Complexity: O(1)

This means the checks take the same amount of time no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding how these checks affect performance helps you write safe and efficient blockchain code, a skill valued in real projects.

Self-Check

"What if the require statement was inside a loop over an array of inputs? How would the time complexity change?"