Pages: [1]   Go Down
Author Topic: Which is 'cheaper': max length char array or counting bytes?  (Read 276 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Jr. Member
**
Karma: 1
Posts: 72
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am reading a line of data from a text file on an SD card that varies between about 20 and 100 bytes (characters) into a char array.  Right now I am simply declaring the char array with a size of 100, but I realize that this is taking up memory that doesn't get used sometimes.  I thought about reading the bytes to count them, setting the array size and then re-reading them into the array, but wondered if this would take more or less resources.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 551
Posts: 46240
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

If the plan is to read all the characters on a line, and then dynamically allocate an array of that size, at some point, you will allocate an array that has room 100 characters. You might as well statically allocate an array of that size, and read the file in half the time.
Logged

Offline Offline
Jr. Member
**
Karma: 1
Posts: 72
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I should have mentioned that 90% of the time, the line will only be 50 characters at most (I am reading song lyrics).  However, I need to allow for the occasional 100 character line.

I was on the page that static allocation was probably cheaper in the end (certainly simpler) but not as elegant.
Logged

California
Offline Offline
Faraday Member
**
Karma: 82
Posts: 3123
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Unless you are starving for those extra 50 bytes of SRAM, going from n to 2n isn't worth it.
Logged

Pages: [1]   Go Up
Jump to: