JavaScript Just In Time compilation

hari picture hari · Oct 18, 2011 · Viewed 21.6k times · Source

I have a quite big JavaScript for HTML page for a device.

But it's a bit slow. I tried compressing JavaScript files but it's still not satisfactory.

So I was thinking, is it possible to make it as a Just in Time that is compiled converted to machine code and use it? (Hope my understanding is correct) I use a WebKit based browser.

Anybody please who have done this, please provide links to "How To" pages or info about the same.

Answer

Spudley picture Spudley · Oct 18, 2011

Both Safari and Chrome do JIT compilation of Javascript already. In fact, the only browser in widespread use that doesn't is IE8 and earlier. This is one of the main reasons why IE8 is so much slower than the competition these days.

But reading between the lines of your question, my guess is that you're not quite understanding what JIT compilation is. JIT compilation happens on the browser; you don't need to change your code in any way at all in order for the browser to be able to do JIT compilation on it for you.

What it sounds like you're actually thinking of is bytecode compilation, such as Java does. This bytecode is effectively a half-way compiled language which is then itself JIT compiled when you run the program. If this is what you're thinking of, I can confirm that this is not an option for browser-based Javascript code.

Google have been toying with a technology called 'Native Client' (NaCl), which would allow you to provide compiled code to the browser, but this is not available yet except in development versions of Chrome.

In any case, compiling may make your code run quicker, but it wouldn't solve the fundamental issue of why it's running slowly, which is likely to be a far better thing to resolve. (even compiled code will perform badly if it has bottlenecks; compilation in itself doesn't magically make slow code better)

If you want to find out why your script is running slowly, I recommend using a profiling tool, such as the one built into Firebug or Chrome's Developer Tools. This will help you identify the parts of your code which are running slowly.

You could also try the YSlow tool, which can also give useful information on javascript performance.

You also state that you've compressed your script to try to get it to go faster. Compressing the script will help it to download quicker (because it's a smaller file), but it won't do anything for the speed that the code runs at.

I hope that helps.