0
0
Blockchain / Solidityprogramming~5 mins

Why data location affects cost in Blockchain / Solidity - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why data location affects cost
O(n)
Understanding Time Complexity

In blockchain, where data is stored can change how much work the system does.

We want to see how data location affects the cost of running code.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


contract Example {
    uint[] storageData;
    uint[] memoryData;

    function updateStorage() public {
        for (uint i = 0; i < storageData.length; i++) {
            storageData[i] = storageData[i] + 1;
        }
    }

    function updateMemory() public {
        uint[] memory temp = memoryData;
        for (uint i = 0; i < temp.length; i++) {
            temp[i] = temp[i] + 1;
        }
    }
}
    

This code updates numbers stored in two places: storage (permanent) and memory (temporary).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the array to update its value.
  • How many times: Once for each element in the array (n times).
How Execution Grows With Input

As the array gets bigger, the loop runs more times, so the work grows with the number of items.

Input Size (n)Approx. Operations
1010 updates
100100 updates
10001000 updates

Pattern observation: The work grows directly with the number of elements.

Final Time Complexity

Time Complexity: O(n)

This means the time to update grows in a straight line as the data size grows.

Common Mistake

[X] Wrong: "Updating data in memory costs the same as updating data in storage."

[OK] Correct: Storage updates are more expensive because they change permanent data on the blockchain, while memory updates are temporary and cheaper.

Interview Connect

Understanding how data location affects cost helps you write efficient blockchain code and shows you know how the system works behind the scenes.

Self-Check

"What if we copied storage data to memory before updating, then wrote back once? How would the time complexity change?"