Contents

Gas Optimization with Bit Operation

Abstract

As we know, storaging data in blockchain is expensive.

In some cutting-edge projects, some hacking methods are used to reduce gas, and the bit operation we are talking about in this article is commonly found in the source code of some header projects.

Introduciton

The representation of uint8 binary is 00000000, where each bit has 0 and 1, we default to 1 when it is true, 0 is false. Therefore, we can manage the bool array in the form of a bitmap to save gas.

Demo Code

Following is the demo code for comparision.

We use bool array and bit operation to manage the same data.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
contract Bitmap {
    bool[8] implementationWithBool;
    uint8 implementationWithBitmap;

    function setDataWithBoolArray(bool[8] memory data) external {
        implementationWithBool = data;
    }

    function setDataWithBitmap(uint8 data) external {
        implementationWithBitmap = data;
    }

    function readWithBoolArray(uint8 index) external returns (bool) {
        return implementationWithBool[index];
    }

    function readWithBitmap(uint indexFromRight) external returns (bool) {
        uint256 bitAtIndex = implementationWithBitmap & (1 << indexFromRight);
        return bitAtIndex > 0;
    }
}

Evaluation

Here are the result while write same data into the uint8 variable and bool array which has the length of 8.

MethodGas FeeNet Gas FeeSave(Compare to setDataWithBoolArray())
setDataWithBitmap437614373915311 (≈26%)
setDataWithBoolArray59050590500

Conclusion

  • It is recommended to use bit operation for partial variable management.