Payable functions in Blockchain / Solidity - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | 10 simple updates |
| 100 | 100 simple updates |
| 1000 | 1000 simple updates |
Pattern observation: Each call takes about the same time, so total work grows linearly with calls.
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.
[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.
Understanding how payable functions work and their time cost helps you explain smart contract efficiency clearly and confidently.
"What if the deposit function also loops through all users to update something? How would the time complexity change?"