The latest beta r153 has a new option to allow you to select a new physics engine powered by asm.js. On Chrome and Firefox it's 2-3x faster than the old engine which was powered by Box2dWeb - fast enough to be close to native speeds, even on mobile! However, a couple of issues have caused us to only provide it as an option, instead of a new default. The reasons are a little involved, so this blog post aims to cover what it is, how it works, why it can be so much faster, and what the current drawbacks are.
What is asm.js?
Asm.js was invented by Mozilla to help web-based applications get closer to the performance of native apps, typically written in C or C++.
Traditionally, a native app would be written in a language like C++, and then the compiler generates CPU instructions from the code. The CPU runs the generated instructions directly, making it really fast (especially since C and C++ are designed to be high-performance languages).
The new asm.js physics option is based around the original C++ Box2D engine compiled to asm.js using Emscripten.
A very useful feature of asm.js is that it makes no allocations at all and never needs any garbage collection. If you switch to the asm.js physics engine, this eliminates the main source of garbage creation, and can eliminate much of the jankiness. That by itself is a very nice benefit, since now even games using physics create very little garbage overall.
So even if your target platform is not Chrome or Firefox and asm.js physics don't appear to be much faster, there are still two good reasons to switch: it reduces garbage to ensure a smooth experience, and it could get a lot faster with future browser updates. However, there are two reasons you also might not want to switch.
So if it's so much faster and better, why is it not simply the new default? The two main drawbacks are the following:
It does not support the 'Disable collisions' action. If you use it when using asm.js physics, it will simply have no effect and the objects will continue to collide. This is simply because the version of the asm.js physics engine we use didn't get this feature compiled in for some reason. We're going to investigate adding support for this, and hopefully can address it in a future release.
The new asm.js physics option is very compelling, and almost justifies being the new default, but we can't do that right now without breaking some existing games or slightly slowing down some iOS games. In short, the physics engine I'd recommend to use is as follows:
- CocoonJS: CocoonJS native physics
- Other iOS native app (e.g. PhoneGap): Box2D web physics
- Anything using 'disable collisions': Box2D web physics
- Otherwise: Box2D asm.js physics