Smart contract concept in Blockchain / Solidity - Time & Space Complexity
When working with smart contracts, it is important to understand how the time to run them changes as the input grows.
We want to know how the contract's execution time scales when it processes more data or users.
Analyze the time complexity of the following code snippet.
contract SimpleStorage {
uint[] public data;
function addData(uint value) public {
data.push(value);
}
function sumData() public view returns (uint) {
uint total = 0;
for (uint i = 0; i < data.length; i++) {
total += data[i];
}
return total;
}
}
This contract stores numbers and sums all stored numbers when asked.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through all stored numbers in the
sumDatafunction. - How many times: It runs once for each number stored in the
dataarray.
As the number of stored numbers grows, the time to sum them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time to sum grows directly with the number of stored numbers.
Time Complexity: O(n)
This means the time to run the sum grows in a straight line as more numbers are stored.
[X] Wrong: "The sum function runs instantly no matter how many numbers are stored."
[OK] Correct: The sum function must look at each number once, so more numbers mean more work and more time.
Understanding how smart contract functions scale with input size helps you write efficient contracts and explain your reasoning clearly.
"What if we stored the running total each time we add a number? How would the time complexity of summing change?"