Return values in Blockchain / Solidity - Time & Space Complexity
When we look at return values in blockchain code, we want to know how the time to get that value changes as the input grows.
We ask: How long does it take to produce the return value when the input size changes?
Analyze the time complexity of the following code snippet.
function getBalance(address user) public view returns (uint) {
return balances[user];
}
This code returns the balance of a user from a stored mapping.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct lookup in a mapping (like a dictionary).
- How many times: Exactly once per call, no loops or repeated steps.
Getting the balance is a simple lookup that does not depend on how many users or balances exist.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same no matter how many users there are.
Time Complexity: O(1)
This means the time to get a return value is constant and does not grow with input size.
[X] Wrong: "Looking up a user's balance takes longer if there are more users."
[OK] Correct: The lookup uses a direct key access, so it takes the same time regardless of total users.
Understanding that return values from mappings are constant time helps you explain efficient data access in blockchain contracts clearly and confidently.
"What if the return value was computed by summing all balances instead of a direct lookup? How would the time complexity change?"