View and pure functions in Blockchain / Solidity - Time & Space 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.
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 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
numbersarray. - Pure function:
getConstant()does not repeat any operation; it just returns a fixed value.
As the array size grows, the number of steps to sum all elements grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to run the view function grows linearly with the input size.
[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.
Understanding how reading data scales helps you write efficient smart contracts and answer questions about cost and speed.
"What if the getSum() function used recursion instead of a loop? How would the time complexity change?"