Timelock pattern in Blockchain / Solidity - Time & Space 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.
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 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.
As the number of queued transactions grows, the time to check and execute them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and possible executions |
| 100 | About 100 checks and possible executions |
| 1000 | About 1000 checks and possible executions |
Pattern observation: The work grows directly with the number of queued transactions.
Time Complexity: O(n)
This means the time to execute grows in a straight line as more transactions are queued.
[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.
Understanding how loops over queued actions affect performance shows you can think about real blockchain contract costs and user experience.
"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?"