2

As part of parsing a JSON response, we are traversing a tree of QVariantMaps. To my understanding, we are creating a copy at each level by calling QVariant::toMap() or qvariant_cast<QVariantMap>(). I would like to optimize this process however I can.

QString parse (QVariant input) {
  QVariantMap map = input.toMap();
  QVariant innerValue = map.value("key");
  QVariantMap subMap = innerValue.toMap();
  QVariant desiredValue = subMap.value("key2");
  
  return desiredValue.toString();
}

Can we avoid copying each map by directly referencing the underlying value inside the QVariant? I assume that we would need a pointer, something like the following:

QString parse (QVariant input) {
  // Assuming we know that input is a map
  QVariantMap* map = getVariantPointer<QVariantMap*>(input); 
  QVariantMap* subMap = getVariantPointer<QVariantMap*>(map->value("key"));

  return getVariantPointer<QString*>(subMap->value("key2"));

Tarod
  • 6,732
  • 5
  • 44
  • 50
Joel Barr
  • 21
  • 2
  • You can optimize your function by passing `QVariant` argument by reference to avoid a copy there. I.e. `QString parse (const QVariant &input)`. – vahancho Nov 20 '20 at 07:44

0 Answers0