Reading contract state in Blockchain / Solidity - Time & Space Complexity
When reading contract state, we want to know how the time to get data changes as the data grows.
We ask: How does reading from the contract slow down when more data is stored?
Analyze the time complexity of the following code snippet.
// Solidity example: reading a value from a mapping
contract SimpleStorage {
mapping(address => uint) public balances;
function getBalance(address user) public view returns (uint) {
return balances[user];
}
}
This code reads a stored balance for a user from the contract's mapping.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct lookup in a mapping (hash table) by key.
- How many times: Exactly once per read call, no loops or recursion.
Reading a value from a mapping 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 data grows larger.
Time Complexity: O(1)
This means reading contract state takes the same time no matter how much data is stored.
[X] Wrong: "Reading a value from a contract gets slower as more data is stored."
[OK] Correct: The mapping lookup is designed to find the value directly without searching through all data, so time stays the same.
Understanding how contract state reads scale helps you explain efficiency in blockchain apps clearly and confidently.
"What if we changed the mapping to an array and searched for the user's balance by looping? How would the time complexity change?"