0
0
Blockchain / Solidityprogramming~5 mins

Function declaration and syntax in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function declaration and syntax
O(n)
Understanding Time Complexity

When we write functions in blockchain code, it's important to know how the time it takes to run changes as the input grows.

We want to find out how the function's running time changes when we give it more data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

function sumArray(uint[] memory numbers) public pure returns (uint) {
    uint total = 0;
    for (uint i = 0; i < numbers.length; i++) {
        total += numbers[i];
    }
    return total;
}

This function adds up all the numbers in an array and returns the total sum.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that goes through each number in the array.
  • How many times: It runs once for every item in the input array.
How Execution Grows With Input

As the array gets bigger, the function does more additions, one for each number.

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

Pattern observation: The work grows directly with the number of items. Double the items, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the input size.

Common Mistake

[X] Wrong: "The function runs in the same time no matter how big the array is."

[OK] Correct: Because the function adds each number one by one, more numbers mean more work and more time.

Interview Connect

Understanding how function time grows with input size helps you explain your code clearly and shows you know how to write efficient blockchain programs.

Self-Check

"What if we changed the function to call itself recursively for each number instead of using a loop? How would the time complexity change?"