Novice question on syntax in sample code

It's also very wasteful.

In these times of 16-core, 64-bit, 5GHz PC processors with 32 or 64GB of ram and 2 or 4 TB of storage, most people don't care about being wasteful any more. But Arduino programming still requires you to think about efficiency.

This array contains 10x10 int variables. Those use 16 bits of memory each, but only values 0 and 1 are used, which needs only 1 bit. So this way of storing the data is only 6% efficient, and 94% is wasted. It takes up 200 bytes of memory.

int a[10][10]={
{0,0,0,1,1,1,0,1,1,1}, //0
{0,0,0,1,0,0,0,0,0,1}, //1
{0,0,0,0,1,1,1,0,1,1}, //2
{0,0,0,1,1,0,1,0,1,1}, //3
{0,0,0,1,0,0,1,1,0,1}, //4
{0,0,0,1,1,0,1,1,1,0}, //5
{0,0,0,1,1,1,1,1,1,0}, //6
{0,0,0,1,0,0,0,0,1,1}, //7
{0,0,0,1,1,1,1,1,1,1}, //8
{0,0,0,1,1,0,1,1,1,1},}; //9

One easy way of making it more efficient would be to use byte instead of int.

byte a[10][10]={
{0,0,0,1,1,1,0,1,1,1}, //0
{0,0,0,1,0,0,0,0,0,1}, //1
{0,0,0,0,1,1,1,0,1,1}, //2
{0,0,0,1,1,0,1,0,1,1}, //3
{0,0,0,1,0,0,1,1,0,1}, //4
{0,0,0,1,1,0,1,1,1,0}, //5
{0,0,0,1,1,1,1,1,1,0}, //6
{0,0,0,1,0,0,0,0,1,1}, //7
{0,0,0,1,1,1,1,1,1,1}, //8
{0,0,0,1,1,0,1,1,1,1},}; //9

This would be 12% efficient and would only waste 88%. Now it takes up only 100 bytes of memory.

This change would make a much bigger difference

int a[10]={
0b0001110111, //0
0b0001000001, //1
...
0b0001101111 }; //9

This would be 62% efficient and waste only 38%. It takes 20 bytes of memory. But it would require changes to the rest of the code, because, as you can see, it's now only a 1-dimensional array, with the second dimension packed bit-wise into int variables.

1 Like