I'm trying to store an array of uint8 but its not very gas efficient. This is my current solution of storing things:

uint8[5] public VALUES = [10, 11, 12, 13, 14];

The problem is that I will have about 40 of these VALUE arrays, and if I test that in Remix, I can't even start the Contract (I've waited minutes for the initialisation and it doesn't occur, so I am assuming this is very inefficient).

My next planned solution is to store the values in a string:

string public VALUES = "1011121314";

And then I would retrieve numbers by getting their index i and i+1, and using parseInt(string) to get the number. But I'm not so sure about the efficiency of doing that.

So since I've heard about assembly being very efficienct within Solidity, I'm wondering if there was a way to store multiple uint8 values in a larger data format, such as a byte32? My current use case is 5 uint8 values, so perhaps byte5 would only be required? Also how would I retrieve such values?

1 Answer
1

Organize the 5 uint8 values in a single struct. When you compile the contract, make sure optimization is turned on. Since storage slots are 32 bytes, the compiler will automatically squidge your uint8s together in storage for maximum gas efficiency.

This approach works. In my test of initialising 5 of those arrays, (total of 30 x uint8), it costed me ~1.28 million gas. Using a struct costed only ~260k gas, giving me a reduction of about 80%.
– pizzaeFeb 5 '18 at 3:36