Why data location affects cost in Blockchain / Solidity - Performance Analysis
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.
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 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).
As the array gets bigger, the loop runs more times, so the work grows with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 updates |
| 100 | 100 updates |
| 1000 | 1000 updates |
Pattern observation: The work grows directly with the number of elements.
Time Complexity: O(n)
This means the time to update grows in a straight line as the data size grows.
[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.
Understanding how data location affects cost helps you write efficient blockchain code and shows you know how the system works behind the scenes.
"What if we copied storage data to memory before updating, then wrote back once? How would the time complexity change?"