简体   繁体   中英

esp32 ram fragmentation handling string

I have had a problem in the past with RAM fragmentation when using the String object so I tested a bit and switched to using the ArduinoJson library.

I have found my program to be stable with ArduinoJson however my code is longer. Therefore I would like to go back to using String and write my answer function by concatenating String variables.

Which of these methods is the best to avoid RAM fragmentation?

Method one:

void server answer (){
    request->send(200, "application/json", "{'data': "+variable+"});
}

Method two:

String Answer;
    
void server answer (){
    Answer = "{ 'data':" + variable + "}"
    request->send(200, "application/json", Answer);
}

Method two-bis:

void server answer (){
    String Answer;
    Answer = "{ 'data':" + variable + "}"
    request->send(200, "application/json", Answer);
}

Method three:

String cretateAnswer(){
    return "{ 'data': + variable + "};
}
void server answer (){
    request->send(200, "application/json", cretateAnswer());
}

I understand what is ram fragmentation, but I don't really understand when this happened and why using String, and how I can avoid it if my library want a String as answer????

PS I wrote this question "on the fly" so if json syntax is wrong or the \ before the ', sorry.

They are all the same. They are all doing exactly the same memory allocations to concatenate strings.

Either you use a buffer on the stack, and use sprintf to build your string

char buff[32];
snprintf(buff, sizeof(buff), "{ \"data\":%d}", variable);
request->send(200, "application/json", buff);

or don't concatenate at all and just send each part right away.

AsyncResponseStream *response = request->beginResponseStream("application/json");
response->print("{ \"data\":");
response->print(variable);
response->print("}");
request->send(response);

or just

AsyncResponseStream *response = request->beginResponseStream("application/json");
response->printf("{ \"data\":%d}", variable);
request->send(response);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM