0
0
Blockchain / Solidityprogramming~5 mins

Timelock pattern in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Timelock pattern
O(n)
Understanding Time Complexity

When using the Timelock pattern in blockchain, it's important to know how the time to execute changes as more actions are queued.

We want to see how the number of queued transactions affects the time to process them.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function executeTransactions() public {
  for (uint i = 0; i < queuedTransactions.length; i++) {
    if (block.timestamp >= queuedTransactions[i].executeAfter) {
      queuedTransactions[i].execute();
      removeTransaction(i);
      i--;
    }
  }
}
    

This code goes through all queued transactions and executes those whose time has come.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of queued transactions.
  • How many times: Once for each transaction in the queue.
How Execution Grows With Input

As the number of queued transactions grows, the time to check and execute them grows too.

Input Size (n)Approx. Operations
10About 10 checks and possible executions
100About 100 checks and possible executions
1000About 1000 checks and possible executions

Pattern observation: The work grows directly with the number of queued transactions.

Final Time Complexity

Time Complexity: O(n)

This means the time to execute grows in a straight line as more transactions are queued.

Common Mistake

[X] Wrong: "Executing transactions takes the same time no matter how many are queued."

[OK] Correct: Because the code checks each transaction one by one, more transactions mean more work and more time.

Interview Connect

Understanding how loops over queued actions affect performance shows you can think about real blockchain contract costs and user experience.

Self-Check

"What if we stored transactions in a data structure that lets us quickly find only those ready to execute? How would the time complexity change?"