Memory allocation in Blockchain / Solidity - Time & Space Complexity
When working with blockchain, memory allocation affects how fast your code runs as it handles data.
We want to know how the time to allocate memory grows when the data size changes.
Analyze the time complexity of the following code snippet.
function allocateMemory(uint size) public {
bytes memory data = new bytes(size);
for (uint i = 0; i < size; i++) {
data[i] = 0x00;
}
}
This code creates a new memory array of a given size and fills it with zeros.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that sets each byte to zero.
- How many times: It runs exactly once for each element in the array, so 'size' times.
As the size of the array grows, the number of steps to fill it grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps to fill |
| 100 | 100 steps to fill |
| 1000 | 1000 steps to fill |
Pattern observation: The work grows directly with the size; doubling the size doubles the steps.
Time Complexity: O(n)
This means the time to allocate and fill memory grows in a straight line with the size of the data.
[X] Wrong: "Memory allocation happens instantly no matter the size."
[OK] Correct: Actually, filling memory takes time for each element, so bigger sizes take longer.
Understanding how memory allocation time grows helps you write efficient blockchain code that handles data well.
"What if we removed the loop that fills the array? How would the time complexity change?"