0
0
Blockchain / Solidityprogramming~5 mins

Smart contract concept in Blockchain / Solidity - Time & Space Complexity

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

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through all stored numbers in the sumData function.
  • How many times: It runs once for each number stored in the data array.
How Execution Grows With Input

As the number of stored numbers grows, the time to sum them grows too.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Pattern observation: The time to sum grows directly with the number of stored numbers.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the sum grows in a straight line as more numbers are stored.

Common Mistake

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

Interview Connect

Understanding how smart contract functions scale with input size helps you write efficient contracts and explain your reasoning clearly.

Self-Check

"What if we stored the running total each time we add a number? How would the time complexity of summing change?"