How can I reference the value of a QVariant without making a copy?

Viewed 335

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"));

0 Answers
Related