0
0
Blockchain / Solidityprogramming~5 mins

Storage layout in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Storage layout
O(1)
Understanding Time Complexity

When working with blockchain storage, it's important to understand how accessing and organizing data affects speed.

We want to know how the time to read or write data changes as the stored data grows.

Scenario Under Consideration

Analyze the time complexity of the following storage access pattern.


// Solidity example
contract StorageExample {
    uint[] public data;

    function addData(uint value) public {
        data.push(value); // add value to storage array
    }

    function readData(uint index) public view returns (uint) {
        return data[index]; // read value at index
    }
}
    

This code stores numbers in a list on the blockchain and allows adding and reading by position.

Identify Repeating Operations

Look at what repeats when using this storage layout.

  • Primary operation: Accessing an element by index in the storage array.
  • How many times: Each read or write accesses one storage slot directly.
How Execution Grows With Input

Accessing or adding data takes about the same time no matter how many items are stored.

Input Size (n)Approx. Operations
101 storage read or write
1001 storage read or write
10001 storage read or write

Pattern observation: The time stays about the same regardless of how many items are stored.

Final Time Complexity

Time Complexity: O(1)

This means reading or writing a single item takes a constant amount of time, no matter how big the storage is.

Common Mistake

[X] Wrong: "Accessing data in a storage array gets slower as the array grows because it has to look through all items."

[OK] Correct: Each item is stored at a fixed position, so the contract can jump directly to it without checking others.

Interview Connect

Understanding storage layout and its time cost helps you design smart contracts that run efficiently and save gas.

Self-Check

"What if we stored data in a linked list instead of an array? How would the time complexity of reading an item change?"