ballercat / walt

:zap: Walt is a JavaScript-like syntax for WebAssembly text format :zap:

Home Page:https://ballercat.github.io/walt/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

bug: the walt file of wasm spended more time than js

CBulFel opened this issue · comments

commented

`

walt:

export function SUM(n: i32): i32 {

let sum: i32 = 0;

let i: i32 = 0;

while(i < n) {
    sum = sum + i;
    i = i + 1;
}

return sum;

}

SUMWalt().then(wasmModule => {
const begin = Date.now()
console.log('wasm begin: ', begin)
console.log('wasm:', wasmModule.instance.exports.SUM(999999999)) // 1
console.log('wasm end: ', Date.now() - begin)
})

js:

function SUM(n) {

let sum = 0;

let i = 0;

while(i < n) {
    sum = sum + i;
    i++;
}

return sum;

}

const begin = Date.now()
console.log('js begin: ', begin)
console.log('js: ', SUM(999999999)) // 1
console.log('js end: ', Date.now() - begin)

`

result:

the SUM funtion return value is not the same, and the wasm time more than js time.

image

If you think that WebAssembly is always faster than pure JS, you are wrong.
I also used to think so, but after experimenting with it, I found out that it's either works with the same speed or slower than JS. The key reason is that JS is rather well optimized and JIT-compiled, so in case of very simple functions like yours, it will be not-slower than WA (or even faster as you write).

Perhaps, it may be faster if you compile a complex program which uses a decent amount of RAM into WA completely. But if it's about simple algorithm you will not get much benefit.

I say it all out of my own experience, which is based on some experiments 2-3 years ago. Maybe now or in the future it will change, but the fact is that JS is very well optimized, but calls to WA functions probably have some overhead, so in case of simple fast functions, there is no benefit from WA.

commented

@CBulFel it really depends on compiler and browser. For example AssemblyScript (wasm) on latest Chrome perform this test 3x faster than JS.

Снимок экрана 2020-10-03 в 20 20 00

See benchmark fiddle: https://webassembly.studio/?f=rx60wjdye9h

PS
Btw more advanced compiler like Clang just fold this code to sum of arithmetic progression which will be equivalent to:

export function sum(n: i32): i32 {
  if (n < 1) return 0;
  return i32(u64(n - 1) * u64(n - 2) / 2) + (n - 1);
}

and perform instantly with O(1) time