Re: Java 200 times faster, almost as easy to use, so why Javascript ?

Forums > Javascript > Java 200 times faster, almost as easy to use, so why Javascript ?
November 11, 2011 | 6:05 pm

Just a quick comment and examples. Hopefully to illustrate some best practices in JS for improved performance.

These JS files you’ve provided make heavy use of global variables, and even then ones which haven’t been scoped with var, The former are slow, and the latter are even slower (and dangerous since they are values shared between instances).

This is true for both the older spidermonkey JS implementation, as well as the new JIT compiled Jaegermonkey implementation. And in the new engine it’s even more important for optimal JIT performance.

I’ve taken a brief moment to revise your examples just comparing your JS with some improved JS files.

Also, some of your examples had codepaths which could possibly be eliminated (e.g. a large loop which sets one variable over and over again, so in effect the only one necessary to set is the final loop value, or if those values are never used in the future, they don’t need to be set at all). So they might not be accurate tests of read/write performance, but rather a test of deadcode elimination. I didn’t have time to investigate whether or not this is the case.

Finally, also when testing you need to execute a function a few times before JS will completely JIT compile, so be sure to execute a few times to get the optimum JIT compiled benchmark.

That said, Java will be faster than JS. No question. I don’t know of any of the new JS implementation which are as fast as the JIT compiled Java VM. Part of this is because of static typing and other language features.

Javascript, however, gains all that nice small talky dynamic typing and binding goodness, and is in many ways more agile than programming in Java, as long as you don’t trip yourself up in the many errors that can happen with dynamic binding when not carefully coded.

Anyway, not trying to get into any language better than another conversation. While I personally mostly code in C, I’m language agnostic. Each language is great for its own reason.

My results with your examples are below:

Calculations test:

Max 5:
old global js:349
revised js:459

Max 6:
old global js: 913
revised js: 11875 (~13x speedup)

Array Fill Test:

Max 5:
old global js:0.53 seconds
revised js:0.33 seconds

Max 6:
old global js: 0.33 seconds
revised js: 0.06 seconds (~5x speedup)

Array Writing Test:

Max 5:
old global js:1658
revised js:3041

Max 6:
old global js: 2240
revised js: 6207 (~3x speedup)

Array Reading Test:

Max 5:
old global js:1249
revised js:3325

Max 6:
old global js: 1684
revised js: 9278 (~5.5x speedup)

Subscribe to the Cycling '74 Weekly Newsletter

Let us tell you about notable Max projects, obscure facts, and creative media artists of all kinds.

* indicates required