Function declaration and syntax in Blockchain / Solidity - Time & Space 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.
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 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.
As the array gets bigger, the function does more additions, one for each number.
| 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 finish grows in a straight line with the input size.
[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.
Understanding how function time grows with input size helps you explain your code clearly and shows you know how to write efficient blockchain programs.
"What if we changed the function to call itself recursively for each number instead of using a loop? How would the time complexity change?"