HTML and CSS Reference
In-Depth Information
Your Code Will Be Compiled and Optimized on the Fly
What happens to your JavaScript code is rather fascinating: first it is compiled in machine language in order to run on
the CPU, and then it may be compiled again, but in a more optimized way if the browser's JavaScript engine judges
this necessary and possible.
The initial compilation generates slow code, then the following compilations generate fast, optimized code, and
whereas on desktop, compilation time is unnoticeable, on mobile, slowdowns are occurring as optimizations are
made and tested by the JavaScript engine.
Your code will run fast only when optimized, and only the functions that are called many times will be optimized
(the engine marks these as hot and optimizes them).
The consequence of this approach is that the JavaScript engine will make optimizations while your game is
Optimizations performed by the compiler are speculative; they are made under the assumption that the JavaScript
state is stable. If the state changes, then the compiler changes the evaluation of your function, which can cause a
deoptimization to occur (called a global deopt).
You can also get deoptimizations if there's some specific part of your function that invalidates the optimization
process, such as a try / catch block (called a local deopt). The engine will continue to attempt to optimize to a specific
threshold and then will give up. Until that time, you can get a plethora of optimize/deopt combos every frame as the
engine tries to understand itself and find a local minimum of execution.
Finding and fixing all this is madness and varies from engine to engine. I suggest that you check out the literature
for each virtual machine (VM) if you see that deopts are causing performance issues (for more information, see the
section “Digging Deeper.”)
Rev Up the Engine
To have your game running at a steady 60FPS from the start, your code will have to be optimized before the start. Or, to
put it differently, the player shouldn't be able to play before the JavaScript engine has optimized your game.
The obvious solution is to have a warm-up phase while the game is loading or displaying a menu. During this
phase, you would run your game in the background so that its code is optimized before the user starts playing.
If you run only a subset of the game during the warm-up phase, only the JavaScript engine will optimize this
subset. Sometimes, it may be enough to call only the most expensive functions, for example, a physics simulation, at
a fast rate during the warm-up phase. But, I would say that the best warm-up is to run the entire game at a fast rate;
however, it may be impractical to do so.
Figure 3-6 displays how Foxes and Shotguns ( ) warms up behind the scenes while
loading assets.
Figure 3-6. Behind the loading screen a special level is generated
Search WWH ::

Custom Search