Struct Ordering Rule
Just like Pack Rule, by fitting variables into the fewest possible storage slots—can result in significant gas savings.
Example
pragma solidity ^0.8.17;
contract PackStruct {
struct PoorlyOrderedStruct {
address router;
uint256 amount;
uint64 timestamp;
}
struct WellOrderedStruct {
uint64 timestamp;
address router;
uint256 amount;
}
PoorlyOrderedStruct poorExample = PoorlyOrderedStruct(address(0), 100, uint64(block.timestamp));
WellOrderedStruct goodExample = WellOrderedStruct(uint64(block.timestamp), address(0), 100);
function readGoodExample() external view returns (WellOrderedStruct memory) {
return goodExample;
}
function readPoorExample() external view returns (PoorlyOrderedStruct memory) {
return poorExample;
}
}
Calling function storereadBadStruct
would cost 1462 gas and calling function readGoodStruct
would cost 4309 gas only, proving that the struct ordering can significantly impact gas consumption.
Test Environment
- Compiler: solc 0.8.17
- Testing Framework: Foundry
ETH saved over 100 transactions
100 tx * 30 gwei * 0.000000001 * (4309-1462) = 0.008541 ~= 0.009 ETH1
USD Saved over 100 transactions
- At \$4000 / ETH: \$36
- At \$3000/ETH: \$27
- At \$2000/ETH: \$19
-
Assumed gas price: 30 gwei ↩