Thursday, June 11, 2020

Javascript is faster than C++

Can Javascript in QML beat C++ in Speed?

Few have challenged that Javascript can be faster than C++. If one takes the challenge literally, C++ is always faster than Javascript. However, with the overhead of Qt libraries and the QML interpreter, performance can skew dramatically.

Can Javascript be faster than C++? Yes. The following are scenarios where code should be in Javascript instead of C++.


Scenarios Where Javascript is Faster Than C++

Looking at the benchmark in the article "Speed Benchmark: Calling QML function versus Javascript function versus QObject", we know that calling .mjs Javascript functions from QML is six times faster than calling QObjects in C++.

The article "Speed Benchmark: Number crunching in QML versus C++" states that the time it takes .mjs Javascript to:
count from zero to one billion is 2.94 seconds.
The article "Speed Benchmark: Calling QML function versus Javascript function versus QObject" states that the time it takes QML to:
call from QML into C++ QObject is 176 seconds.
Taking away the time it takes to call a .mjs Javascript object from QML, the time difference between QML calling .mjs Javascript functions and C++ QObject is:
176 seconds - 51 seconds = 126 seconds

Conclusion

We can conclude that .mjs Javascript is able to count from zero to one billion four times to equal to the time it takes QML to call into C++ QObject. Put differently, in the time it takes for QML to call into C++ QObjects, Javascript is able to
count from zero to 4 billion.
However, QML does not call into C++ QObjects just one time. For every slot that is called, there is likely a signal that gets emitted back into QML. Therefore, we should double the number of computations Javascript is able to perform. That is, in the time it takes for QML to call a C++ QObject slot and receive a resulting emitted signal, Javascript is able to:
count from zero to 8 billion.

What Should Be Written In Javascript?

Anything that is equal to or less than counting from zero to 8 billion should be written in Javascript. These include:

  • Boolean states of UI objects that do not need to be serialized to disk
  • "Enum" equivalents of UI states
  • Simple computation like division, addition or multiplication of multiple UI states
  • Simple string manipulation
More importantly, custom QML Themes and palettes where colors are stored (and probably is read-only during runtime) should be in .mjs Javascript objects!

This begs the question - "Why is Qt implementing Theme in C++"? Maybe Qt is performing much more than just color matching. Maybe Theme has to interoperate with Qt Quick Control 2 whose core modules are in C++.

A Note to C++ Developers

C++ may be fast but do not succumb to the urge to write an application where QML is a totally dumb UI and everything is performed in C++. This is quite common in many Qt development teams.



No comments: