Gas and transaction fees in Blockchain / Solidity - Time & Space 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.
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 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.
As the number of actions grows, the total gas calculation takes longer because it adds each action's cost.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of actions.
Time Complexity: O(n)
This means the time to calculate gas grows in a straight line as more actions are added.
[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.
Understanding how gas calculation scales helps you explain blockchain transaction costs clearly and shows you know how work grows with input size.
"What if the actions array was sorted by gas cost before summing? Would the time complexity change?"