Using a Global String with .reserve to avoid heap

I'm using Esp8266 and UniversalTelegramBot, and I've read about the 'evil String' and I was just wondering what about declare a Global String responsible for sending the messages to the user and count the bigger one,and just put a .reserve(N) globally to always keep the same memory for it to avoid heap fragmentation. Or should I use the .reserve(N) just locally ?
I know I will always have that 'N memory' blocked even not using it all if I've declared it globally but do you think it's worth ? Or should I just use it locally and I will have the same result ?

String::reserve does not avoid the heap, but using a global instance as a "permanent" one can avoid fragmentation, if you grab the max-ever-to-use heap space early and never alter it. You have to ensure you never need more; in that case, String will have to re-alloc, and all that effort might be for nothing.

Is it worth it? If doing nothing special, you were never going to run out, even in atypical (but short of pathological) use, then no :slight_smile:

You can call c_str() on it periodically to see if the pointer ever changes, indicating a re-alloc happened.

So why not to use a "classic", traditional char array strings?

You could use a .reserve on a global String.
But when you don't need the String globally, just use the String and .reserve() locally in your function.

In my opinion this is one of the worst advice on String.
If he reserves a differente size for the String, let's say a smaller one, then it will free the rest, that could be used by other variables. This means that the next time he will need the full space for the String, it won't be able to be expanded, so re-alloc will appear.

I think you should define it globally (if needed), reserve the maximum space ever, and never touch its size. Also, try not to use '+' but '.concat()' or '+=' for your operations.

You should take a look at this Website that explains pretty well how to safely use String

And this is what I dislike.
When you don't need a variable( or instance) globally, don't define it globally.

I agree, but I answered to the OP request :slight_smile:

In your quote you purposely (I guess) left apart the "if needed".
The best would still define the String as static in local function if doable. Or define it at the begining of the request and use a reference for the next used functions