State variables in Blockchain / Solidity - Time & Space Complexity
When working with state variables in blockchain, it's important to know how the cost of accessing and updating them changes as your contract grows.
We want to understand how the number of operations changes when we read or write state variables.
Analyze the time complexity of the following code snippet.
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
This contract stores a number in a state variable and allows setting and getting its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Reading or writing the single state variable
storedData. - How many times: Each function call accesses the variable once; no loops or repeated operations inside.
Since the contract only reads or writes one variable, the number of operations stays the same no matter how many times you call the functions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 read or write |
| 100 | 1 read or write |
| 1000 | 1 read or write |
Pattern observation: Each operation costs the same regardless of how many times it happens; no extra work is added as input grows.
Time Complexity: O(1)
This means accessing or updating a state variable takes the same amount of time no matter what.
[X] Wrong: "Accessing state variables gets slower as the contract stores more data."
[OK] Correct: Each state variable access is direct and does not depend on how many variables exist or how many times you have accessed it before.
Understanding that state variable access is constant time helps you reason about contract efficiency and gas costs, a key skill for blockchain developers.
"What if the contract stored an array of values and you needed to update all of them? How would the time complexity change?"