0
0
Blockchain / Solidityprogramming~5 mins

Gas usage testing in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Gas usage testing
O(n)
Understanding Time 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?

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 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 adds each number to the total.
  • How many times: It runs once for every element in the input array.
How Execution Grows With Input

As the array gets bigger, the number of additions grows the same way.

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

Pattern observation: The work grows directly with the number of items in the array.

Final Time Complexity

Time Complexity: O(n)

This means the gas cost grows in a straight line as the input size increases.

Common Mistake

[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.

Interview Connect

Understanding how gas usage grows helps you write efficient contracts and explain your code clearly in interviews.

Self-Check

"What if we changed the function to sum only the first half of the array? How would the time complexity change?"