Emitting events in Blockchain / Solidity - Time & Space Complexity
When working with blockchain, emitting events helps record important actions. Understanding how the time to emit events grows with more data is key.
We want to know how the cost changes as we emit more events or include more information.
Analyze the time complexity of the following code snippet.
contract Example {
event DataStored(address indexed user, uint256 data);
function storeData(uint256[] calldata dataList) external {
for (uint i = 0; i < dataList.length; i++) {
emit DataStored(msg.sender, dataList[i]);
}
}
}
This code emits an event for each item in a list, recording who sent it and the data value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that emits an event for each data item.
- How many times: Once for every element in the input list.
Each new data item causes one event emission, so the work grows steadily as the list grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 event emissions |
| 100 | 100 event emissions |
| 1000 | 1000 event emissions |
Pattern observation: The number of operations grows directly with the number of data items.
Time Complexity: O(n)
This means the time to emit events grows in a straight line as you add more data items.
[X] Wrong: "Emitting multiple events at once is just as fast as emitting one event."
[OK] Correct: Each event costs time and resources, so more events mean more work and longer execution.
Understanding how event emissions scale helps you write efficient smart contracts and explain your reasoning clearly in interviews.
"What if we emitted only one event with all data combined instead of one per item? How would the time complexity change?"