Why events communicate contract activity in Blockchain / Solidity - Performance Analysis
When smart contracts run, they often send out events to share what happened inside. Understanding how the time to process these events grows helps us see how efficient this communication is.
We want to know: how does the cost of sending events change as more events happen?
Analyze the time complexity of the following code snippet.
contract Example {
event ActionDone(address user, uint amount);
function performActions(uint[] calldata amounts) external {
for (uint i = 0; i < amounts.length; i++) {
// Some logic here
emit ActionDone(msg.sender, amounts[i]);
}
}
}
This code emits an event for each item in the input list, communicating each action done by the user.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop that goes through each amount and emits an event.
- How many times: Once for every element in the input array.
Each new input item causes one event to be emitted, so the work grows evenly with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 events emitted |
| 100 | 100 events emitted |
| 1000 | 1000 events emitted |
Pattern observation: The number of operations grows directly with the input size.
Time Complexity: O(n)
This means the time to emit events grows in a straight line as the number of events increases.
[X] Wrong: "Emitting events is free or constant time no matter how many events are sent."
[OK] Correct: Each event costs time and resources, so more events mean more work and longer execution.
Knowing how event emission scales helps you explain contract efficiency and gas costs clearly, a useful skill when discussing smart contract design.
"What if we emitted only one event after the loop summarizing all actions? How would the time complexity change?"