0
0
Blockchain / Solidityprogramming~5 mins

Gas optimization with storage in Blockchain / Solidity - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Gas optimization with storage
O(n)
Understanding Time 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.

Scenario Under Consideration

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

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

Each new item causes one storage write, so more items mean more writes.

Input Size (n)Approx. Operations
1010 storage writes
100100 storage writes
10001000 storage writes

Pattern observation: The number of operations grows directly with input size.

Final Time Complexity

Time Complexity: O(n)

This means the time and gas cost grow in a straight line as you add more data.

Common Mistake

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

Interview Connect

Understanding how storage operations scale helps you write efficient smart contracts that save gas and run smoothly on blockchain.

Self-Check

"What if we batch multiple items into one storage slot? How would the time complexity change?"