0
0
Blockchain / Solidityprogramming~5 mins

State variables in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: State variables
O(1)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
101 read or write
1001 read or write
10001 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.

Final Time Complexity

Time Complexity: O(1)

This means accessing or updating a state variable takes the same amount of time no matter what.

Common Mistake

[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.

Interview Connect

Understanding that state variable access is constant time helps you reason about contract efficiency and gas costs, a key skill for blockchain developers.

Self-Check

"What if the contract stored an array of values and you needed to update all of them? How would the time complexity change?"