While restucturing a part of my code into a class I chose to change a static sized array into a dynamic array and was shocked about the size of my sketch, which increased by ~579%!
Now there is some discussion going on about wheather to use new
or malloc()
but I did not find a hint to this massive increase in sketch size.
- So, if anybody would like to explain where this huge increase is comming from, that would be great!
- Further, if anybody knows simmilar pitfalls, it would be very nice of you to share ;)
Here is a demo code to check for yourselfs:
void setup() {
// put your setup code here, to run once:
#define BUFLEN 8 * sizeof(char)
#define BUFVAL '5'
#define BUFARR {BUFVAL,BUFVAL,BUFVAL,BUFVAL,BUFVAL,BUFVAL,BUFVAL,BUFVAL,0}
#define MODE 2
int i = 0;
Serial.begin(115200);
#if (MODE == 0)
//10.772 Bytes for an Arduino Due on IDE 1.57 -> 2% of total
char empty_page[BUFLEN+1] = BUFARR;
#elif (MODE == 1)
//12.772 Bytes for an Arduino Due on IDE 1.57 -> 2% of total, ~18.5% increase
char *empty_page = (char *)malloc(BUFLEN+1);
memset(empty_page, BUFVAL, BUFLEN);
empty_page[BUFLEN+1] = '\0'; // NULL Terminate
#elif (MODE == 2)
//73.152 Bytes for an Arduino Due on IDE 1.57 -> 13% of total, ~579% increase
char *empty_page = new char[BUFLEN+1]BUFARR;
#endif
Serial.println("Result: ");
for(i=0; i<BUFLEN; i++) {
Serial.print(empty_page[i]);
}
Serial.println("");
#if (MODE == 1)
free(empty_page);
#elif (MODE == 2)
delete[] empty_page;
#endif
}
void loop() {
// put your main code here, to run repeatedly:
}
To check this code without arduino: http://ideone.com/e.js/bMVi0d
EDIT:
My understanding is, that new
leads the IDE to compile in some large c++ stuff in order to handle it. On the other hand, the verbose compiler output of the IDE is identical.
I am trying to minimize my sketches, anybody else with this goal would sure be interested as well in parts like ´new´ that you need to avoid in order to get a smaller sketch. This seems to be a general Arduino IDE thing, so there should be a more meta explaination for it.