Variable packing helps save space by putting small pieces of data close together in one place. This makes programs use less memory and run faster.
Variable packing in Blockchain / Solidity
contract Example {
uint128 a;
uint128 b;
uint256 c;
}Variables declared one after another with smaller sizes can be packed into a single 256-bit storage slot.
Packing works best when variables are declared in order from smallest to largest size.
contract Packed {
uint128 a;
uint128 b;
}contract NotPacked {
uint256 a;
uint128 b;
}contract Mixed {
uint64 a;
uint64 b;
uint128 c;
}This contract packs two 128-bit variables a and b into one storage slot, saving space. The function getSum returns their sum plus c.
pragma solidity ^0.8.0; contract VariablePacking { uint128 public a = 1; uint128 public b = 2; uint256 public c = 3; function getSum() public view returns (uint256) { return a + b + c; } }
Variable packing reduces gas costs by using fewer storage slots.
Always declare smaller variables together before larger ones to maximize packing.
Packing only works for state variables stored on the blockchain, not for local variables.
Variable packing saves space by storing multiple small variables in one slot.
It helps reduce gas costs and improve contract efficiency.
Order your variables from smallest to largest to get the best packing.