Search code examples
javascriptjvmwebassembly

Why the JVM cannot be used in place of WebAssembly?


As far as I understood, JavaScript cannot be compiled ahead of time because of it's dynamic nature. So Interpretation and just in time compilation happens at run time, that affects JavaScript performance. So WebAssembly comes into picture. Languages can be compiled ahead of time into intermediate format (WASM). This gives good performance since there is less runtime overhead.

My question is why JVM cannot be used in place of WebAssembly VM. Java compiled into intermediate format (bytecode). This byte code can be given to browser and JVM can execute it. JVM also supports JIT which helps to achieve near native performance. 

So what is the need for new WebAssembly. Why can't JVM be integrated into browser and achieve high performance by leveraging the existing most popular Java language.


Solution

  • There are a great many reasons why the JVM was not deemed a suitable runtime in place of WebAssembly ...

    • WebAssembly was designed with delivery-over-HTTP and browser-based in mind. For that reason, it supports streaming compilation - i.e. you can start compiling the code while downloading.
    • WebAssembly was designed to have rapid compilation times (resulting in web pages that load quickly), this is supported by having very simple validation rules compared to Java / JVM languages.
    • WebAssembly was designed with the concept of a 'host' environment, i.e. the browser.
    • WebAssembly was designed to be secure and simple, minimising the overall attack surface.
    • WebAssembly was designed to support a great many languages (C, C++, Rust, ...), whereas the JVM was initially design for a single language, Java.

    As a general observation, WebAssembly was designed to support multiple languages on the web. The JVM was designed to support Java on the desktop. It doesn't make either one better than the other in a more general sense.

    Finally, the JVM was integrated with the browser (Java Applets), but that didn't work out in the end!