I'm exploring the Arduino String class and I've written the following two cases. I want to know which case is efficient and not causing memory fragmentation at all?
Thanks in Advance!
The variables l, m, n, o are constant for the following two cases. However, for my project these variables won't remain constant, they will change as per the user input in the webpage and I'm a bit worried about the memory fragmentation issue.
Case 1:
float l = 7.568, m = 99.7864;
byte n[] = "ESP32 ESP8266", o[] = "Arduino Mega";
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println( pc(F("a01")) );
Serial.println( pc(F("a02")) );
Serial.println( pc(F("a03")) );
Serial.println( pc(F("a04")) );
Serial.println();
delay(1000);
}
String pc(const String& var) {
if (var == F("a01")) {
return String(l, 3);
}
else if (var == F("a02")) {
return String(m, 4);
}
else if (var == F("a03")) {
return String((char *)n);
}
else if (var == F("a04")) {
return String((char *)o);
}
return String();
}
Case 2:
float l = 7.568, m = 99.7864;
byte n[] = "ESP32 ESP8266", o[] = "Arduino Mega";
String str((char *)0);
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
str.reserve(100);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println( pc(F("a01")) );
Serial.println( pc(F("a02")) );
Serial.println( pc(F("a03")) );
Serial.println( pc(F("a04")) );
Serial.println();
delay(1000);
}
String pc(const String& var) {
str.clear(); //str = "";
if (var == F("a01")) {
return str += String(l, 3);
}
else if (var == F("a02")) {
return str += String(m, 4);
}
else if (var == F("a03")) {
return str += String((char *)n);
}
else if (var == F("a04")) {
return str += String((char *)o);
}
return String();
}
I think the first solution will be the best. Operation with stings use a lot of time and resources.
Check safeString library, it's a better version of String default library
Then using any of the mentioned libraries rather than using either String class or revamping the code from the beginning (c-strings or array of char) , isn't the best choice?
And what about using Arduino's built-in String library for the robust microcontrollers like ESP8266 or ESP32?
No, AVR is an Atmel thing. It is not only the available memory that differs, AVR uses a simple bootloader to launch the code directly on the hardware, whereas ESP's are running an operating system (RTOS) which then handles code execution. AVR uses a very crude memory management compared to ESP's which is more advanced.