bblanchon / ArduinoJson

📟 JSON library for Arduino and embedded C++. Simple and efficient.
https://arduinojson.org
MIT License
6.63k stars 1.1k forks source link

Return JsonDocument from class methods #2106

Closed Laxilef closed 1 week ago

Laxilef commented 1 week ago

Hi,

Question about optimization when returning JsonDocument from class methods. Let's say there is code:

JsonDocument Bot::getUpdates(long offset, unsigned short limit) {
  JsonDocument payload;
  payload["offset"] = offset;
  payload["limit"] = limit;

  unsigned short timeout = 0;
  if (this->longPollTime > 0) {
    payload["timeout"] = this->longPollTime;
    timeout = this->longPollTime * 1000u + this->timeout;
  }

  auto response = this->sendRequest("POST", "getUpdates", payload, timeout);
  if (!response.isNull() && response.is<JsonArray>()) {
    // some code
  }

  return response;
}

JsonDocument Bot::getUpdates(long offset) {
  return this->getUpdates(offset, this->messagesLimit);
}

JsonDocument Bot::getUpdates() {
  return this->getUpdates(this->offset + 1, this->messagesLimit);
}

In the first Bot::getUpdates() method I create a JsonDocument and the other methods are helpers. If I understand correctly, then every time the JsonDocument will be copied at each nesting level and create an extra load? The problem is that there can be more nesting levels. Would it be more correct to pass JsonDocument by reference to a method or is there a more elegant way? Thank you!

bblanchon commented 1 week ago

Hi @Laxilef,

The second and third getUpdates() overloads won't create copies of the returned JsonDocument because of the copy elision mechanism. Even if copy elision didn't trigger, JsonDocument is move-contructible, so it would not produce a copy.

Passing by reference would work, too, but it would be less elegant.

Best regards, Benoit

Laxilef commented 1 week ago

Thanks!