Arduino IDE Code/memory efficiency

Attempt to test code efficiency on Arduino IDE. Here I want to turn on 8 leds: from 0,1,4,5,6,7,8,13.

Sketch uses 740 bytes (9%) of program storage space. Maximum is 8,192 bytes.
Global variables use 9 bytes (1%) of dynamic memory, leaving 503 bytes for local variables. Maximum is 512 bytes.

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(13, OUTPUT);
  
}

void loop() {
  digitalWrite(0, HIGH);
  digitalWrite(1, HIGH);
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(6, HIGH);
  digitalWrite(7, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(13, HIGH);  
  
}

Sketch uses 730 bytes (8%) of program storage space. Maximum is 8,192 bytes.
Global variables use 17 bytes (3%) of dynamic memory, leaving 495 bytes for local variables. Maximum is 512 bytes.

byte ledOut[8]={0,1,4,5,6,7,8,13}; //map out 8 led pins

void setup() {
for (byte x=0; x<8;x++){
  pinMode(ledOut[x], OUTPUT);}   
 
}

void loop() {
for (byte x=0; x<8;x++){
  digitalWrite(ledOut[x], HIGH);}  

}

Sketch uses 86 bytes (1%) of program storage space. Maximum is 8,192 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 512 bytes for local variables. Maximum is 512 bytes.

int main (void)
{
   DDRD = 0b11110011; // set pin 0, 1, 4,5,6,7 as output
   DDRB = 0b00100001; // set pin 8, 13 as output
   
   PORTD |= 0b11110011; // turn pin 0, 1, 4,5,6,7 On
   PORTB |= 0b00100001; // turn pin 8, 13 on
}

So?

Mark

Of course a sketch where you copy the pin numbers into an array is going ot use more memory. But, it makes iterating over the pins far easier.

Bypassing the digitalWrite() and pinMode() functions will result in smaller code, AS LONG AS YOU DON"T INTEND TO PORT THAT TO ANOTHER ARDUINO. If you do, good luck.

TANSTAAFL. You get what you pay for.

I'm with Mark: "So?" The Arduino code (which contains a bunch of initialization that your "bare C" code doesn't do) is a whopping 700 bytes bigger than a more minimal implementation. That's one of the reasons that the default Arduino chip these days are 32k of program memory - so you don't have to fuss about such things.

The advantage of the last code, at the cost of readability, is a massive performance improvement. (Although the readability can be improved by using #define preprocessors to define pin numbers and _BV() macros to set values at no cost to performance).

There have been occasions where I've been running a chip's clock at ~16MHz and the digitalWrite function is just too damn slow! I also found it great fun and enlightening to work with the bitwise operators. Of course, as mentioned previously, you seriously lose portability and readability, so for most situations the library functions are perfectly sufficient.