Gas optimization with storage in Blockchain / Solidity - Time & Space Complexity
When working with blockchain, saving and reading data from storage costs gas, which affects how fast and cheap your code runs.
We want to understand how the number of storage operations changes as the data size grows.
Analyze the time complexity of the following code snippet.
contract StorageExample {
uint[] public data;
function addData(uint[] memory newData) public {
for (uint i = 0; i < newData.length; i++) {
data.push(newData[i]);
}
}
}
This code adds each item from a new array into storage one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop that pushes each item into storage.
- How many times: Once for each item in the input array.
Each new item causes one storage write, so more items mean more writes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 storage writes |
| 100 | 100 storage writes |
| 1000 | 1000 storage writes |
Pattern observation: The number of operations grows directly with input size.
Time Complexity: O(n)
This means the time and gas cost grow in a straight line as you add more data.
[X] Wrong: "Adding many items at once costs the same as adding one item."
[OK] Correct: Each storage write costs gas, so more items mean more cost and longer execution.
Understanding how storage operations scale helps you write efficient smart contracts that save gas and run smoothly on blockchain.
"What if we batch multiple items into one storage slot? How would the time complexity change?"