0
0
Blockchain / Solidityprogramming~5 mins

Storage vs memory usage in Blockchain / Solidity - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Storage vs memory usage
O(n)
Understanding Time Complexity

When working with blockchain, it's important to know how using storage and memory affects how long your code takes to run.

We want to see how the time needed changes when we use storage or memory for data.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

contract Example {
    uint[] storageData;

    function addToStorage(uint value) public {
        storageData.push(value);
    }

    function sumStorage() public view returns (uint) {
        uint sum = 0;
        for (uint i = 0; i < storageData.length; i++) {
            sum += storageData[i];
        }
        return sum;
    }

    function sumMemory(uint[] memory data) public pure returns (uint) {
        uint sum = 0;
        for (uint i = 0; i < data.length; i++) {
            sum += data[i];
        }
        return sum;
    }
}

This contract stores numbers in blockchain storage and sums them either from storage or from memory.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

As the number of elements grows, the time to sum them grows too.

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

Pattern observation: The time grows directly with the number of items; doubling items doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum the array grows in a straight line with the number of elements.

Common Mistake

[X] Wrong: "Accessing storage and memory costs the same time per element."

[OK] Correct: Reading from storage is slower and costs more gas than reading from memory, so loops over storage take more time and resources.

Interview Connect

Understanding how storage and memory affect time helps you write efficient blockchain code and shows you know how to manage costs and speed.

Self-Check

"What if we copied the storage array to memory before summing? How would the time complexity change?"