To explore the method of

WebAssembly by name but never practiced. In my opinion, most front-end developers are familiar with scripting languages, not C, C++, Rust, etc.

It would be nice to have a way to compile the source code into WebAssembly using JS. So, after a long search, I found walt.

walt

AssemblyScript is a subset of TypeScript that Walt can use to write code and compile it automatically.

For details, see github.com/ballercat/w…

Uh… This article will be a bit difficult to write, may have to look at the source.

Wrote a few lines of code in Walt, seems to keep getting it wrong, official documentation is not rich enough, don’t know how to solve it, decided to explore other methods.

Abandon Walt to use AssemblyScript

Exploring a bit more, I found a way to write WebAssembly in TypeScript without using Walt. See the url on the front: github.com/AssemblyScr…

The idea is to use the ASC tool to generate a.wasm file from assemblyScript and load it as js readable code using new webassembly.instance () and new webassembly.module (). The final call is js.

Record a piece of code that loads. Wasm and calls its methods.

fetch('./module.optimized.wasm')
        .then(response => response.arrayBuffer())
        .then(function(result){
            console.log(result);
            let myModule = new WebAssembly.Instance(new WebAssembly.Module(result, {}));
            console.log(myModule.exports.add());
        });
Copy the code

Full source code address

Contrast test

When Fibonacci test n is set to 50, native JS takes 243727 ms and WebAssembly takes 87325 ms. The performance difference is huge.

You’ll have to test C and JAVA against it again when you have time.

Cry, JAVA in the same environment in just over 40,000 milliseconds.

language The value of n Time (ms)
js 50 243727
WebAssembly 50 87325
JAVA 50 40000
C

In this test, the computing speed of WebAssembly is about three times that of JS and half that of JAVA, which is a great improvement in performance.

But why is it slower than JAVA? Personally, I think the performance bottleneck lies in the WebAssembly compiler.

You should take a closer look at the WebAssembly compiler later.

There are still a lot of questions to be answered, such as: does native speed refer to a certain programming language or machine code speed?

The article will continue to be updated, the source text address

References:

  1. www.ibm.com/developerwo…

  2. AssemblyScript Project home page