Gas Optimization Tips

In Ethereum, the execution of contract will cost gas fee. An excellent contract should cost gas fee as low as possible.

In this article, I will summary some gas optimization tips.

1 Storage Optimization

In Ethereum, storage data is written in contract account, which will cost the most gas fee.

1.1 Reduce writing storage data

We can use memory to storage middle data, instead of always writing storage data.

uint256 a = storageVar;  // read storage
a += 10;                  // memory operation
storageVar = a;           // write storage

1.2 Merge Variable

Solidity aligns storage slots on 32-byte boundaries, multiple uint8 or bool values can be packed into the same slot.

struct Packed {
    uint128 a;
    uint128 b;
}

1.3 Use memory instead of Storage

Use memory instead of Storage except the storage variable is necessary.

2 For-each Optimization

Use mapping instead of for-each searching array.

Mapping does not occupy continuous storage space, and read/write operations are relatively inexpensive.

3 Function call Optimization

3.1 Short circuit

If there are other judgment conditions before function call, we can prioritize judgment of prerequisite conditions.

if (a > 10 && expensiveCheck()) { ... }

3.2 Function modifier

External is cheaper than Public.

Pure and View not cost gas fee.

4 Data type Optimization

Use minimum sufficient data type. Like uint8, uint16 are more storage space-efficient than uint256.

5 Event Optimization

5.1 Index

Use as little as possible indexed parameter.

Index will cost more gas fee.

5.2 Emit

Avoid frequent emit large events

6 Contract Structure Optimization

6.1 Use contract library

6.2 Inheritance chain flattening

Multi-level inheritance will increase deployment Gas.

7 Bytes And Array

7.1 Bytes is more efficient than string

7.2 Swap And Pop

Use swap-and-pop instead of dynamic deletion.

But this way will disorder the sequence.

function remove(uint index) public {
    arr[index] = arr[arr.length - 1];
    arr.pop();
}

8 Unchecked

Using unchecked to skip overflow checking can save gas fee.

unchecked { i++; }