Advanced Techniques to Optimize Gas Costs on Ethereum

ยท

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;
    }
}
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;
    }
}

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:


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


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 refund

FAQ 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.