Packing variables helps save gas by storing multiple small values together in one storage slot. This reduces the cost of storing data on the blockchain.
0
0
Packing variables for gas savings in Blockchain / Solidity
Introduction
When you have several small variables like booleans or small integers in a smart contract.
When you want to reduce the gas cost of writing data to the blockchain.
When optimizing smart contracts for cheaper deployment and transactions.
When you want to store multiple flags or counters efficiently.
When working with structs that have many small fields.
Syntax
Blockchain / Solidity
contract Example {
// Variables packed into one 32-byte slot
uint8 a;
uint8 b;
uint16 c;
bool d;
}Variables of smaller size (like uint8, bool) can be packed together if declared consecutively.
Order matters: place smaller variables together to fit into one 32-byte storage slot.
Examples
All variables fit into one 32-byte slot because their sizes add up to less than 32 bytes.
Blockchain / Solidity
contract Packed {
uint8 a;
uint8 b;
uint16 c;
bool d;
}uint256 uses a full slot, so b and c will be stored in a new slot, increasing gas cost.
Blockchain / Solidity
contract NotPacked {
uint256 a;
uint8 b;
bool c;
}uint128 x and y each take half a slot, z and flag can be packed together in the next slot.
Blockchain / Solidity
struct Data {
uint128 x;
uint128 y;
uint8 z;
bool flag;
}Sample Program
This contract packs four small variables into one storage slot to save gas. The getValues function returns all values.
Blockchain / Solidity
pragma solidity ^0.8.0; contract GasSaver { // Packed variables uint8 public a = 1; uint8 public b = 2; uint16 public c = 300; bool public d = true; // Function to get all values function getValues() public view returns (uint8, uint8, uint16, bool) { return (a, b, c, d); } }
OutputSuccess
Important Notes
Always declare smaller variables together to maximize packing.
Changing variable order can reduce or increase gas costs.
Use tools like Remix or Hardhat to check gas usage before and after packing.
Summary
Packing variables reduces gas by storing multiple small variables in one slot.
Order and size of variables affect packing efficiency.
Good packing leads to cheaper smart contract deployment and transactions.