0
0
Blockchain / Solidityprogramming~5 mins

Payable functions in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Payable functions
O(1)
Understanding Time Complexity

When we use payable functions in blockchain, we want to know how the cost of running them changes as more data or users interact with them.

We ask: How does the time to process payments grow when the function is called many times?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


contract SimpleWallet {
    mapping(address => uint) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }
}
    

This code lets users send money to the contract and keeps track of each user's balance.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Updating the balance for the sender in a mapping.
  • How many times: Once per function call, no loops or recursion inside.
How Execution Grows With Input

The function does a simple update each time it is called, no matter how many users or deposits happened before.

Input Size (n)Approx. Operations
1010 simple updates
100100 simple updates
10001000 simple updates

Pattern observation: Each call takes about the same time, so total work grows linearly with calls.

Final Time Complexity

Time Complexity: O(1)

This means each call to the payable function takes the same small amount of time, no matter how many deposits happened before.

Common Mistake

[X] Wrong: "Payable functions get slower as more users deposit money because the contract stores more balances."

[OK] Correct: The contract updates only one user's balance each time, so it does not loop through all users. The time stays the same.

Interview Connect

Understanding how payable functions work and their time cost helps you explain smart contract efficiency clearly and confidently.

Self-Check

"What if the deposit function also loops through all users to update something? How would the time complexity change?"