Variable Type Ordering Impacts Gas Consumption
EVM attempts to pack variables into the same storage slot. When a slot's 32-byte capacity is exceeded, it moves to the next slot. Consider this optimization:
contract MyContract {
uint64 public a;
uint64 public b;
uint64 public c;
uint64 public d;
function test() {
a = 1;
b = 2;
c = 3;
d = 4;
}
}- Single SSTORE Operation: All variables fit in one storage slot.
contract MyContract {
uint64 public a;
uint64 public b;
byte e;
uint64 public c;
uint64 public d;
function test() {
a = 1;
b = 2;
c = 3;
d = 4;
}
}- Three SLOTs Required: The
byte edisrupts packing, requiring two SSTORE operations.
Pro Tip
Group related variable updates together to minimize storage operations:
function test() {
a = 1;
b = 2;
// ... intermediate operations
c = 3;
d = 4; // Triggers another SSTORE
}Leverage High-Order Bits for Flags
Store additional data in unused parameter bits:
- Gas Formula:
n * 68 + (32-n) * 4bytes (wheren= parameter count) - Example: Replace
addresswith a struct utilizing high-order bits for flags.
Optimal Hashing Algorithms
Gas consumption hierarchy: ripemd160 > sha256 > keccak256
๐ Learn more about EVM opcode costs
Short-Circuit Evaluation
Place cheaper operations first in logical expressions:
// OR: Stop if f(x) is true
f(x) || g(y)
// AND: Stop if f(x) is false
f(x) && g(y)External vs Public Functions
- Public Functions: Copy parameters to memory (gas cost).
External + Calldata: Avoid memory copies:
function process(address calldata user) external {}
Minimize External Calls
Batch requests to external contracts:
// Preferred
function getMultipleData() external returns (uint, uint, bool) {}
// Avoid
function getValueA() external view returns (uint);
function getValueB() external view returns (uint);Storage Cleanup Incentives
Use delete to reclaim storage space and receive gas refunds:
delete myStorageArray[index]; // Earns gas refundFAQ Section
Why does variable ordering affect gas costs?
EVM storage slots are 32-byte aligned. Proper packing reduces expensive SSTORE operations.
Is keccak256 always the cheapest hash?
Yes, among standard cryptographic hashes. For non-crypto needs, consider cheaper alternatives.
How significant are gas refunds from storage deletion?
Refunds cap at 20% of transaction gas used. Strategic deletions can notably reduce net costs.