Packing variables for gas savings in Blockchain / Solidity - Time & Space Complexity
When writing smart contracts, saving gas means saving money. Packing variables helps reduce storage cost.
We want to see how packing affects the number of operations as data size grows.
Analyze the time complexity of this Solidity snippet packing variables:
contract Packed {
uint128 a;
uint128 b;
uint256 c;
function setValues(uint128 _a, uint128 _b, uint256 _c) public {
a = _a;
b = _b;
c = _c;
}
}
This code packs two 128-bit variables into one 256-bit storage slot, then sets values.
Look for repeated actions that cost gas.
- Primary operation: Writing to storage slots.
- How many times: Three assignments happen, but two fit in one slot.
As you add more variables, storage writes increase.
| Input Size (variables) | Approx. Storage Writes |
|---|---|
| 2 (packed) | 1 |
| 3 (unpacked) | 3 |
| 10 (packed) | 5 |
Pattern observation: Packing reduces the number of storage writes roughly by grouping variables.
Time Complexity: O(n)
This means the number of storage writes grows linearly with the number of variables, but packing reduces the constant factor.
[X] Wrong: "Packing variables changes the time complexity class."
[OK] Correct: Packing only reduces how many times you write, but the growth still depends on the number of variables.
Understanding how packing affects gas cost shows you know how to write efficient smart contracts, a valuable skill in blockchain development.
"What if we added dynamic arrays instead of fixed variables? How would the time complexity change?"