Gas usage testing in Blockchain / Solidity - Time & Space Complexity
When testing gas usage in blockchain smart contracts, we want to know how the cost changes as the input grows.
We ask: How does the gas needed increase when the contract processes 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 numbers in an array and returns the total sum.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that adds each number to the total.
- How many times: It runs once for every element in the input array.
As the array gets bigger, the number of additions grows the same way.
| 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 in the array.
Time Complexity: O(n)
This means the gas cost grows in a straight line as the input size increases.
[X] Wrong: "Gas cost stays the same no matter how many items are processed."
[OK] Correct: Each item requires work, so more items mean more gas is used.
Understanding how gas usage grows helps you write efficient contracts and explain your code clearly in interviews.
"What if we changed the function to sum only the first half of the array? How would the time complexity change?"