Storage vs memory usage in Blockchain / Solidity - Performance Comparison
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.
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 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).
As the number of elements grows, the time to sum them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time grows directly with the number of items; doubling items doubles the work.
Time Complexity: O(n)
This means the time to sum the array grows in a straight line with the number of elements.
[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.
Understanding how storage and memory affect time helps you write efficient blockchain code and shows you know how to manage costs and speed.
"What if we copied the storage array to memory before summing? How would the time complexity change?"