I've read that the Arduino String is bad as it causes memory fragmentation, so I try to avoid them mostly. But I still have some occurences where I'm not quite sure if they are ok after all.
The first is in print statements:
I have a function which prints a success or error message to the serial port, like so: Serial.println("Success");
. Is this ok or should I (for example) pre define the String using #define SUCCESS "SUCCESS"
?
Which leads me to the next case, defines:
I'm using MQTT and have the topics defined like above, e.g. #define TOPIC_COLOR "light/color"
. Is this fine?
A third one is with ArduinoJSON:
I'm using Strings as keys, like so lights["red"] = redVal;
. This call is made at multiple places so I assume the string would be created multiple times? A workaround/improvement I've thought of is using an enum defining the properties and using that as key.
Thanks for all comments, tips and explanations!
1 Answer 1
+1 to @majenko's comments. I tend to avoid the String
class, as I like to know what is actually going on, and I stick to char *
and char []
in general (and the stdlib
functions like sprintf
, strlen
, etc).
Couple of notes on your question:
"foo/bar"
is fine. Some characters have special meanings in the C language itself, so you need to escape them with the\
. For example if"
was part of your literal string, you'd write"foo\"bar\""
I tend to use
ArduinoJSON
to parse. If my app is just sending JSON payloads, I just build it withsprintf
orprint
which results in smaller programs. But, I guess it is a matter of choice. It is a great library.
-
Thanks! I'm using ArduinoJSON to parse and send, but also to store the current state, it's quite handy that it does all those things. As of now, storage is enough, if it gets sparse I'll have to think of something else...matthesinator– matthesinator2021年05月24日 22:13:09 +00:00Commented May 24, 2021 at 22:13
String
class.String
objects that problems occur. I don't know what ArduinoJSON does with string indices, though. On smaller MCUs (AVR) you should useF("stringliteral")
to reduce RAM usage whenever possible, though.