Variable packing in Blockchain / Solidity - Time & Space Complexity
When working with blockchain, how we store variables can affect how fast our code runs.
We want to see how packing variables together changes the work the program does.
Analyze the time complexity of the following code snippet.
struct Data {
uint128 a;
uint128 b;
}
function storeData(Data[] memory dataList) public {
for (uint i = 0; i < dataList.length; i++) {
// store each packed data item
}
}
This code stores a list of data items where two 128-bit numbers are packed together in one struct.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop over each element in the dataList array.
- How many times: Once for each item in the input list (n times).
As the number of data items grows, the loop runs more times, doing more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input size grows.
[X] Wrong: "Packing variables makes the loop run faster and changes time complexity."
[OK] Correct: Packing reduces storage size but the loop still runs once per item, so time grows the same way.
Understanding how variable packing affects performance shows you know both storage and execution costs, a useful skill in blockchain development.
"What if the dataList contained nested arrays inside each item? How would the time complexity change?"