Nominate our 2022 Qt Champions!

Fastest way to compare QVariant with UserType

  • I'm looking for a very fast way to compare two QVariants that wrap the same user type.

    What do you think about the following approaches:
    @bool operator==() const(const QVariant &rhs)
    if(myData.userType() == qMetaTypeId<MyUserType>())
    bool method1 = static_cast<MyUserType>(myData.constData()) == static_cast<const MyUserType>(rhs.myData.constData());

    bool method2 = myData.value<MyUserType>() == rhs.myData.value<MyUserType>();
    return something

    I would think that the first approach is faster, because no deep copy or ctor call is necessary. It is more risky because of the static_cast and kind of a hack though.

    I took a look into the Qt implementation of the second method, but as far as I could see, at least once the copy ctor of MyUserType is called.

  • Well... why don't you try and see? Seems like something to just try out and doing some measurements on.

  • Moderators

    i would also tend to the second comparison.
    But you should add "QVariant::canConvert()": checks before comparing the values.

  • Thanks for the answers guys.

    I took the advice to compare the two approaches by stepping through them. The result is pretty clear.
    The first approach first calls QVariant::constData() twice (for each side) and then MyClass::operator==() is called.

    The second approach takes several steps, including multiple checks and a ctor call for each side before !!! method 1 is used (with a reinterpret_cast instead of a static_cast though).

    I think I'll stick to the first method, because it is faster and the comparing of the MetaTypeIds beforehand should in my case be enough to avoid illegal static_casts.

Log in to reply