Event filtering in Blockchain / Solidity - Time & Space Complexity
When working with blockchain events, filtering helps us find specific information quickly.
We want to know how the time to filter events changes as the number of events grows.
Analyze the time complexity of the following code snippet.
// Assume events is an array of event objects
function filterEvents(events, targetAddress) {
let filtered = [];
for (let i = 0; i < events.length; i++) {
if (events[i].address === targetAddress) {
filtered.push(events[i]);
}
}
return filtered;
}
This code goes through all events and collects those matching a specific address.
- Primary operation: Looping through each event once.
- How many times: Exactly once for every event in the list.
As the number of events grows, the time to check each event grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the number of events.
Time Complexity: O(n)
This means the time to filter events grows in a straight line as the number of events increases.
[X] Wrong: "Filtering events is instant no matter how many events there are."
[OK] Correct: Each event must be checked, so more events mean more work and more time.
Understanding how filtering scales helps you explain how blockchain apps handle large data efficiently.
"What if events were stored in a map by address? How would the time complexity change?"