Storage vs memory vs calldata in Blockchain / Solidity - Performance Comparison
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.
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.
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.
As the input array gets bigger, the loop runs more times, copying each element.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 copies |
| 100 | 100 copies |
| 1000 | 1000 copies |
Pattern observation: The number of operations grows directly with the size of the input.
Time Complexity: O(n)
This means the time to copy data grows linearly as the input size increases.
[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.
Understanding how data location affects time cost helps you write efficient smart contracts and shows you know how blockchain resources work.
What if we changed the function to copy data directly from calldata to storage without using memory? How would the time complexity change?