Storage layout in Blockchain / Solidity - Time & Space 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.
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.
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.
Accessing or adding data takes about the same time no matter how many items are stored.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 storage read or write |
| 100 | 1 storage read or write |
| 1000 | 1 storage read or write |
Pattern observation: The time stays about the same regardless of how many items are stored.
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.
[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.
Understanding storage layout and its time cost helps you design smart contracts that run efficiently and save gas.
"What if we stored data in a linked list instead of an array? How would the time complexity of reading an item change?"