[Interest] Can QML compiler optimize switch into array indexing?
Elvis Stansvik
elvstone at gmail.com
Thu Oct 14 21:13:22 CEST 2021
Den tors 14 okt. 2021 kl 09:49 skrev Ulf Hermann <ulf.hermann at qt.io>:
>
> Hi,
>
> Let's look at the QML snippet again:
>
> > enabledBorders: {
>
> > switch (control.edge) {
>
> > case Qt.BottomEdge:
>
> > return PlasmaCore.FrameSvgItem.TopBorder;
>
> > case Qt.RightEdge:
>
> > return PlasmaCore.FrameSvgItem.LeftBorder;
>
> > case Qt.TopEdge:
>
> > return PlasmaCore.FrameSvgItem.BottomBorder;
>
> > case Qt.LeftEdge:
>
> > default:
>
> > return PlasmaCore.FrameSvgItem.RightBorder;
>
> > }
>
> > }
>
> What the QML interpreter and JIT do on such a thing is quite sad:
>
> 1. Lookup "Qt" and figure out it's a singleton.
> 2. Lookup "BottomEdge" on "Qt" and figure out it's an enum
> 3. Resolve enum to number
> 4. Compare
>
> ... and so on for all the cases. Once the right case is found, it does:
>
> 1. Lookup "PlasmaCore" and figure out it's a type namespace (probably?)
> 2. Lookup "FrameSvgItem" on "PlasmaCore" and figure out it's a type
> 3. Lookup "TopBorder" on "FrameSvgItem" and figure out it's an enum
> 4. Resolve enum to number
>
> The lookups are cached, so the second and any following executions of
> the same piece of code are faster. Yet, it's still quite far from what
> it could be. The problem here is that the QML engine initially doesn't
> know what all the names mean and has to figure it out at run time.
>
> This is a case where the QML-to-C++ compilation will truly shine because
> we can do all of the lookup at compile time if we know all your types.
> Then the generated code collapses into a few comparisons on plain integers.
>
> This is why you have to declare your types in your header files using
> QML_ELEMENT and friends, and use qt_add_qml_module to declare QML
> modules in CMake.
I now saw your nice blog post about this at [1], saying "You should
not call qmlRegisterType() and friends procedurally anymore.".
I then saw that there's no pointer in the docs for qmlRegisterType and
friends [2] to QML_ELEMENT.
If the recommended way nowadays is the declarative approach, would
probably be good with a pointer there since not everyone finds the
blog posts.
Maybe I should just make a suggestion on Gerrit, but it was such a
long time since I had it set up, so I'll take the lazy way out :)
Cheers,
Elvis
[1] https://www.qt.io/blog/qml-type-registration-in-qt-5.15
[2] https://doc.qt.io/QT-5/qqmlengine.html#qmlRegisterType
>
> best regards,
> Ulf
> _______________________________________________
> Interest mailing list
> Interest at qt-project.org
> https://lists.qt-project.org/listinfo/interest
More information about the Interest
mailing list