0
0
Blockchain / Solidityprogramming~5 mins

Gas and transaction fees in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Gas and transaction fees
O(n)
Understanding Time Complexity

When working with blockchain, gas and transaction fees affect how much work a transaction requires.

We want to understand how the cost grows as transactions do more work.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

function executeTransaction(actions) {
  let totalGas = 0;
  for (let i = 0; i < actions.length; i++) {
    totalGas += actions[i].gasCost;
    // perform action
  }
  return totalGas;
}

This code calculates the total gas needed by adding up gas costs for each action in a transaction.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each action in the transaction.
  • How many times: Once for every action in the list.
How Execution Grows With Input

As the number of actions grows, the total gas calculation takes longer because it adds each action's cost.

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

Pattern observation: The work grows directly with the number of actions.

Final Time Complexity

Time Complexity: O(n)

This means the time to calculate gas grows in a straight line as more actions are added.

Common Mistake

[X] Wrong: "Gas calculation time stays the same no matter how many actions there are."

[OK] Correct: Each action adds work, so more actions mean more time to add up gas costs.

Interview Connect

Understanding how gas calculation scales helps you explain blockchain transaction costs clearly and shows you know how work grows with input size.

Self-Check

"What if the actions array was sorted by gas cost before summing? Would the time complexity change?"