0
0
Blockchain / Solidityprogramming~5 mins

Variable packing in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

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.

When you want to store many small values efficiently in a smart contract.
When you want to reduce the cost of storing data on the blockchain.
When you want to optimize your contract to use less gas.
When you have multiple small variables that can fit together in one storage slot.
When you want to improve performance by reducing storage reads and writes.
Syntax
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.

Examples
Two 128-bit variables packed into one 256-bit slot.
Blockchain / Solidity
contract Packed {
    uint128 a;
    uint128 b;
}
Variables not packed because uint256 uses a full slot first.
Blockchain / Solidity
contract NotPacked {
    uint256 a;
    uint128 b;
}
Two 64-bit and one 128-bit variables packed together in one slot.
Blockchain / Solidity
contract Mixed {
    uint64 a;
    uint64 b;
    uint128 c;
}
Sample Program

This contract packs two 128-bit variables a and b into one storage slot, saving space. The function getSum returns their sum plus c.

Blockchain / Solidity
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;
    }
}
OutputSuccess
Important Notes

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.

Summary

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.