Monitoring deployed contracts in Blockchain / Solidity - Time & Space Complexity
When monitoring deployed contracts, we want to know how the time to check contract events grows as more events happen.
We ask: How does monitoring cost change when the number of contract events increases?
Analyze the time complexity of the following code snippet.
// Pseudocode for monitoring contract events
function monitorEvents(contractAddress, fromBlock, toBlock) {
events = blockchain.getEvents(contractAddress, fromBlock, toBlock)
for (event of events) {
process(event)
}
}
This code fetches all events from a contract between two blocks and processes each event one by one.
- Primary operation: Looping through all events returned from the blockchain.
- How many times: Once for each event between fromBlock and toBlock.
As the number of events grows, the time to process them grows roughly the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 event processings |
| 100 | 100 event processings |
| 1000 | 1000 event processings |
Pattern observation: The work grows directly with the number of events.
Time Complexity: O(n)
This means the time to monitor events grows in a straight line with the number of events.
[X] Wrong: "Monitoring events takes the same time no matter how many events there are."
[OK] Correct: Each event must be processed, so more events mean more work and more time.
Understanding how monitoring scales helps you design systems that stay fast as data grows, a key skill in real projects.
"What if we only monitor events from the last 10 blocks instead of a large range? How would the time complexity change?"