Is it possible to run JavaScript code in parallel in the browser? I'm willing to sacrifice some browser support (IE, Opera, anything else) to gain some edge here.
Here's a quick example of what running code in parallel in JavaScript looks like. This will execute promise1, promise2, and promise3 in parallel. Then, it will combine the response from each promise together into an array.
Javascript can only work in a single thread and there is no way to actually have two functions running in parallel. You need to make one call and then the other.
If you run code in the UI thread, there won't ever run anything in parallel. If you want to run code in parallel, you can utilize web workers. A single web worker is also just one thread, if you want to run multiple functions in parallel, you need a new web worker instance for each.
If you don't have to manipulate the dom, you could use webworkers ... there's a few other restrictions but check it out @ http://ejohn.org/blog/web-workers/
Parallel.js has a nice API for multithreaded processing in Javascript. It runs both in web browsers and in node.
Perhaps it would be better to recode your JavaScript in something that generally runs faster, rather than trying to speed up the Javascript by going parallel. (I expect you'll find the cost of forking parallel JavaScript activities is pretty high, too, and that may well wipe out any possible parallel gain; this is common problem with parallel programming).
Javascript is interpreted in most browsers IIRC, and it is dynamic on top of it which means it, well, runs slowly.
I'm under the impression you can write Java code and run it under browser plugins. Java is type safe and JIT compiles to machine code. I'd expect that any big computation done in Javascript would run a lot faster in Java. I'm not specifically suggesting Java; any compiled language for which you can get a plug in would do.
As an alternative, Google provides Closure, a JavaScript compiler. It is claimed to be a compiler, but looks like an optimizer to me and I don't know much it "optimizes". But, perhaps you can use that. I'd expect the Closure compiler to be built into Chrome (but I don't know for a fact) and maybe just running Chrome would get your JavaScript compiler "for free".
EDIT: After reading about what about Closure does, as compiler guy I'm not much impressed. It looks like much of the emphasis is on reducing code size which minimizes download time but not necessarily performance. The one good thing they do in function inlining. I doubt that will help as much as switching to a truly compiled langauge.
EDIT2: Apparantly the "Closure" compiler is different than the engine than runs JavaScript in Chrome. I'm told, but don't know this for a fact, that the Chrome engine has a real compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With