[Interest] Can QML compiler optimize switch into array indexing?

Ulf Hermann ulf.hermann at qt.io
Thu Oct 14 09:48:26 CEST 2021


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.

best regards,
Ulf


More information about the Interest mailing list