0
0
Blockchain / Solidityprogramming~5 mins

Structs in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Structs
O(1)
Understanding Time Complexity

When working with structs in blockchain code, it's important to know how the time to access or process them changes as they grow.

We want to understand how the program's work grows when handling structs with more data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct Transaction {
  address sender;
  address receiver;
  uint amount;
}

Transaction[] public transactions;

function addTransaction(address _to, uint _amount) public {
  transactions.push(Transaction(msg.sender, _to, _amount));
}
    

This code defines a struct for transactions and adds new transactions to a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding a new struct to the end of an array.
  • How many times: Each call adds one transaction; no loops or traversals happen during add.
How Execution Grows With Input

Adding one transaction takes about the same time no matter how many transactions are already stored.

Input Size (n)Approx. Operations
101 operation per add
1001 operation per add
10001 operation per add

Pattern observation: The time to add a transaction stays about the same as the list grows.

Final Time Complexity

Time Complexity: O(1)

This means adding a new struct is quick and does not slow down as more data is stored.

Common Mistake

[X] Wrong: "Adding a struct to an array takes longer as the array grows because it has to check all items."

[OK] Correct: Adding to the end of an array is direct and does not require checking existing items, so time stays constant.

Interview Connect

Understanding how structs and arrays behave helps you explain how data is stored and accessed efficiently in blockchain programs.

Self-Check

"What if we searched for a transaction by sender in the array? How would the time complexity change?"