# Optimising repetitive code

I was wondering if anyone could help out with some optimising tips for repetitive code?

In my project I have alot of code that looks like this:

``````       bitWrite(i, 0, j);
bitWrite(i, 1, k);
bitWrite(i, 2, l);
bitWrite(i, 3, m);
bitWrite(i, 4, n);
bitWrite(i, 5, o);
bitWrite(i, 6, p);
bitWrite(i, 7, q);
``````

Would using a for loop be more efficient for memory? With this example bit of code I want to set the individual bit values and move on but does the fact that I am address different bits with variables limit me to this direct style of coding?

Any pointers would be great, Thanks in advance !

Pointers… no, you don’t want pointers yet

Arrays are your friend. Instead of a, b, c, d, e etc, use bitVal[0], bitVal[1] bitVal[2] etc, or in a loop:

``````byte val = 0;
byte bitVal[8] = {1, 0, 0, 1, 1, 1, 0, 1};

for (byte i = 0; i < 8; i++) {
bitWrite(val, i, bitVal[i]);
}
``````

Would using a for loop be more efficient for memory?

Check the memory used after compiling your code. Make your changes then check new memory used again.

majenko:
Pointers… no, you don’t want pointers yet

Arrays are your friend. Instead of a, b, c, d, e etc, use bitVal[0], bitVal[1] bitVal[2] etc, or in a loop:

``````byte val = 0;
``````

byte bitVal[8] = {1, 0, 0, 1, 1, 1, 0, 1};

for (byte i = 0; i < 8; i++) {
bitWrite(val, i, bitVal[i]);
}

Haha, yes, pointers was a bad choice of phrasing !

Thank you very much that is very interesting and actually brings up another point -

In my arrays in my code I have declared variables for every possible array location so that I could overwrite them later. Is this unnecessary? Can I initialize an array with all 0’s or 1’s for instance then overwrite it later in the code?

So this…

``````byte a1 = 0;
byte a2 = 0;
byte a3 = 0;
byte a4 = 0;
byte a5 = 0;
byte a6 = 0;
byte a7 = 0;
byte a8 = 0;
byte a9 = 0;
byte a10 = 0;
byte a11 = 0;
byte a12 = 0;

byte myArray [2][3][2] =

{
{//Bank 1
{A1, A2},
{A3, A4},
{A5, A6}
},
{//Bank 2
{A7, A8},
{A9,A10},
{A11,A12}
}
},

A1 = 1;
``````

Becomes:

``````byte myArray [2][3][2] =

{
{//Bank 1
{0, 0},
{0, 0},
{0, 0}
},
{//Bank 2
{0, 0},
{0, 0},
{0, 0}
}
},

MyArray [0][0][0] = 1;
``````

I will test this out but I imagine skipping all of those extra global variables will save me a fair bit of memory or will the compiler create a ‘variable’ each time I reference a point in the array during my main loop and result in the same memory useage?

One more thing, if I am saving the array contents to EEPROM can I still: initialize the array globally, then write code to load previously saved initial values from EEPROM in the setup(){} function?

Edited: for clarity.

if you need to split a number in bits that can be done in the loop too

``````byte val = 0;
byte bitVal = 42;

for (byte i = 0; i < 8; i++)
{
bitWrite(val, i, bitVal & ( 1 << i) );  // 1 << i  creates a bit mask that is  1,2,4,8,16,32,...
}
``````