When you have really small snippets of code that are repeated several times in your micro controller program, is it better to write a method? I mean better in terms of performance and storage usage. I know that when programming for PC, code repetition is a big no go, but what about micro controllers?
In the following example (Arduino Nano with Adafruit 2,8" cap touch display) the snippet should look if the back button is pressed in several screens. I checked in the Arduino IDE how much storage each version takes:
Version 1, 15114 Bytes for complete program:
void battScreen(TS_Point p){
// some other code
// ....
if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
screen = MAIN1;
showMainScreen();
}
}
}
void alarmScreen(TS_Point p){
// some other code
//...
if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
screen = MAIN1;
showMainScreen();
}
}
}
void pumpScreen(TS_Point p){
// some other code
// ...
if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
screen = MAIN1;
showMainScreen();
}
}
}
Version 2, 15234 Bytes for complete program:
void checkBack(TS_Point p){
if ((p.x > backBox.posx) && (p.x < backBox.posx + backBox.sidex)){
if((p.y > backBox.posy) && (p.y < backBox.posy + backBox.sidey)){
screen = MAIN1;
showMainScreen();
}
}
}
void battScreen(TS_Point p){
// some other code
// ...
checkBack(p);
}
void alarmScreen(TS_Point p){
// some other code
// ...
checkBack(p);
}
void pumpScreen(TS_Point p){
// some other code
// ...
checkBack(p);
}
As you can see, version 2 with the extra method takes 120 Bytes more storage. Is there a rule of thumb when it makes sense to create a new method instead of copying code?