Structs in Blockchain / Solidity - Time & Space 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.
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 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.
Adding one transaction takes about the same time no matter how many transactions are already stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 operation per add |
| 100 | 1 operation per add |
| 1000 | 1 operation per add |
Pattern observation: The time to add a transaction stays about the same as the list grows.
Time Complexity: O(1)
This means adding a new struct is quick and does not slow down as more data is stored.
[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.
Understanding how structs and arrays behave helps you explain how data is stored and accessed efficiently in blockchain programs.
"What if we searched for a transaction by sender in the array? How would the time complexity change?"