0
0
Blockchain / Solidityprogramming~5 mins

Emitting events in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Emitting events
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Each new data item causes one event emission, so the work grows steadily as the list grows.

Input Size (n)Approx. Operations
1010 event emissions
100100 event emissions
10001000 event emissions

Pattern observation: The number of operations grows directly with the number of data items.

Final Time Complexity

Time Complexity: O(n)

This means the time to emit events grows in a straight line as you add more data items.

Common Mistake

[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.

Interview Connect

Understanding how event emissions scale helps you write efficient smart contracts and explain your reasoning clearly in interviews.

Self-Check

"What if we emitted only one event with all data combined instead of one per item? How would the time complexity change?"