ERC-20 fungible token standard in Blockchain / Solidity - Time & Space Complexity
When working with ERC-20 tokens, it's important to understand how the time to execute token operations changes as the number of users or transactions grows.
We want to know how the cost of common token actions scales with input size.
Analyze the time complexity of the following ERC-20 transfer function.
function transfer(address to, uint256 amount) public returns (bool) {
require(balances[msg.sender] >= amount, "Insufficient balance");
balances[msg.sender] -= amount;
balances[to] += amount;
emit Transfer(msg.sender, to, amount);
return true;
}
This function moves tokens from one user to another by updating balances and emitting an event.
Look for loops or repeated steps inside the function.
- Primary operation: Access and update two entries in a mapping (balances).
- How many times: Exactly once per transfer call, no loops or recursion.
The function always does the same fixed number of steps regardless of how many users or tokens exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 steps |
| 100 | 5 steps |
| 1000 | 5 steps |
Pattern observation: The number of operations stays the same no matter how many users or tokens there are.
Time Complexity: O(1)
This means the transfer function takes the same amount of time no matter how many tokens or users exist.
[X] Wrong: "The transfer time grows as more users hold tokens because balances get bigger."
[OK] Correct: Each transfer only updates two specific balances directly, so the number of users does not affect the time.
Understanding that token transfers run in constant time helps you explain efficiency in blockchain operations clearly and confidently.
"What if the transfer function also iterated over all token holders to update some data? How would the time complexity change?"