0
0
Blockchain / Solidityprogramming~5 mins

Storage vs memory vs calldata in Blockchain / Solidity - Performance Comparison

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

When working with blockchain smart contracts, how data is stored and accessed affects how long operations take.

We want to understand how the choice between storage, memory, and calldata changes the time cost as data size grows.

Scenario Under Consideration

Analyze the time complexity of the following Solidity function that copies an array from calldata to memory and then to storage.


function copyArray(uint[] calldata input) external {
    uint[] memory temp = new uint[](input.length);
    for (uint i = 0; i < input.length; i++) {
        temp[i] = input[i];
    }
    storedArray = temp;
}
    

This function copies an array received as calldata into memory, then saves it to storage.

Identify Repeating Operations

Look for loops or repeated steps that grow with input size.

  • Primary operation: The for-loop copying each element from calldata to memory.
  • How many times: Exactly once for each element in the input array.
How Execution Grows With Input

As the input array gets bigger, the loop runs more times, copying each element.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to copy data grows linearly as the input size increases.

Common Mistake

[X] Wrong: "Accessing storage, memory, or calldata all take the same time regardless of data size."

[OK] Correct: Storage access is slower and costs more gas because it writes to blockchain state, while memory and calldata are faster but still depend on data size when copying.

Interview Connect

Understanding how data location affects time cost helps you write efficient smart contracts and shows you know how blockchain resources work.

Self-Check

What if we changed the function to copy data directly from calldata to storage without using memory? How would the time complexity change?