Mappings in Blockchain / Solidity - Time & Space Complexity
When working with mappings in blockchain, it's important to know how fast we can find or store data.
We want to understand how the time to access or update a mapping changes as it grows.
Analyze the time complexity of the following code snippet.
mapping(address => uint) public balances;
function updateBalance(address user, uint amount) public {
balances[user] = amount;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
This code stores and retrieves a user's balance using a mapping from addresses to numbers.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct access to mapping entries by key (address).
- How many times: Each access or update happens once per call, no loops involved.
Accessing or updating a mapping entry takes about the same time no matter how many entries exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant even as the mapping grows larger.
Time Complexity: O(1)
This means accessing or updating a mapping entry takes the same short time no matter how many items are stored.
[X] Wrong: "Accessing a mapping gets slower as it stores more data."
[OK] Correct: Mappings use a hash-like structure that lets the program jump directly to the data, so size does not slow access.
Understanding that mappings provide quick access helps you explain efficient data handling in blockchain smart contracts.
"What if we replaced the mapping with an array and searched for the user each time? How would the time complexity change?"