Gas Optimization with Bit Operation
Contents
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.
|
|
Evaluation
Here are the result while write same data into the uint8 variable and bool array which has the length of 8.
Method | Gas Fee | Net Gas Fee | Save(Compare to setDataWithBoolArray()) |
---|---|---|---|
setDataWithBitmap | 43761 | 43739 | 15311 (≈26%) |
setDataWithBoolArray | 59050 | 59050 | 0 |
Conclusion
- It is recommended to use bit operation for partial variable management.