3

Currently, I am iterating through a vector in order to convert it to a QJsonArray:

QJsonArray toJson(const std::vector<unsigned short>& myVec) {
    QJsonArray result;
    for(auto i = myVec.begin(); i != myVec.end(); i++) {
        result.push_back((*i));
    }
    return result;
}

However, this causes a small lag spike in my program. Is there an alternative method to receive a QJsonArray with the data from a vector? (It doesn't need to be a deep copy.)

Griffort
  • 1,174
  • 1
  • 10
  • 26

1 Answers1

5

I am afraid there is no faster way than the one you designed. QJsonArray consists of QJsonValue values, that can encapsulate native values of different types: Null, Bool, Double, String, ..., Undefined. But std::vector consists of values of one only type. Therefore each value of a vector should be converted to QJsonValue individually, and there is no faster way like memcopy.

In any case you may shorten your function.

QJsonArray toJson(const std::vector<unsigned short>& myVec) {
    QJsonArray result;
    std::copy (myVec.begin(), myVec.end(), std::back_inserter(result));
    return result;
}
Phidelux
  • 2,043
  • 1
  • 32
  • 50
273K
  • 29,503
  • 10
  • 41
  • 64
  • Ah, so the slowness is due to the fact that each value needs to be converted to a QJsonValue? – Griffort Mar 24 '18 at 05:59
  • Exactly. Moreover `QJsonArray` API does not provide `emplace_back` that would be faster than `push_back`. – 273K Mar 24 '18 at 06:31
  • 1
    One possible area for optimization could be the memory allocation. `QJsonArray` doesn't have a way to "reserve" N elements at once, but `QVariantList` does - and QJsonArray has a somewhat optimized static function `QJsonAray::fromVariantList`. Worth testing at least. – Daniel Waechter Apr 04 '18 at 00:29