Skip to main content

Storage Variable Packing Optimization.

Description

Packing storage variables into a smaller number of storage slots can significantly reduce gas costs. Solidity stores storage variables using a 256-bit (32-byte) word, so if a storage variable takes up less than 32 bytes, the remaining space in that word is wasted. By packing smaller variables together in the same storage slot, we can reduce the amount of wasted space and therefore reduce gas costs.

Example Code

Consider the following example where we have four storage variables - two uint8's and two bools:

contract Example {
uint8 public var1;
bool public var2;
bool public var3;
uint8 public var4;
}

In this case, each variable takes up 1 byte, but each is stored in a separate 32-byte word, resulting in a total of 128 bytes of storage. However, by packing var1 and var4 into the same storage slot and var2 and var3 into another, we can reduce the storage to just 64 bytes:

contract Example {
struct PackedVars {
uint8 var1;
uint8 var4;
bool var2;
bool var3;
}
PackedVars public packedVars;
}

Recommendation

It is recommended to pack storage variables into smaller numbers of storage slots in order to reduce gas costs. However, it is important to consider the trade-off between gas costs and code complexity. In some cases, packing variables together may make the code more difficult to read and maintain, so it is important to weigh the benefits and drawbacks before making this optimization.