0
0
Blockchain / Solidityprogramming~5 mins

View and pure functions in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: View and pure functions
O(n)
Understanding Time Complexity

When working with blockchain smart contracts, view and pure functions let us read data without changing it.

We want to understand how the time to run these functions grows as the input size grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


contract Example {
    uint[] numbers;

    function getSum() public view returns (uint) {
        uint sum = 0;
        for (uint i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }
        return sum;
    }

    function getConstant() public pure returns (uint) {
        return 42;
    }
}
    

This contract has a view function that sums all numbers in an array and a pure function that returns a fixed number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop in getSum() that goes through each number in the array.
  • How many times: Once for each element in the numbers array.
  • Pure function: getConstant() does not repeat any operation; it just returns a fixed value.
How Execution Grows With Input

As the array size grows, the number of steps to sum all elements grows too.

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 run the view function grows linearly with the input size.

Common Mistake

[X] Wrong: "View and pure functions always run instantly no matter the input size."

[OK] Correct: While pure functions with fixed work run quickly, view functions that loop over data take longer as data grows.

Interview Connect

Understanding how reading data scales helps you write efficient smart contracts and answer questions about cost and speed.

Self-Check

"What if the getSum() function used recursion instead of a loop? How would the time complexity change?"