Con la llegada de wasm, la maquina virtual tendra que correr 2 tipos diferentes de codigo:
JS y wasm
fetch('module.wasm').then(response =>
response.arrayBuffer()
).then(bytes =>
WebAssembly.instantiate(bytes, importObject)
).then(results => {
// Call an exported function:
results.instance.exports.exported_func();
// or access the buffer contents of an exported memory:
var i32 = new Uint32Array(results.instance.exports.memory.buffer);
// or access the elements of an exported table:
var table = results.instance.exports.table;
console.log(table.get(0)());
});
JS
wasm
decoding WebAssembly takes less time than parsing JavaScript.
Compiling and optimizing takes less time because WebAssembly is closer to machine code than JavaScript and already has gone through optimization on the server side.
Reoptimizing doesn’t need to happen because WebAssembly has types and other information built in, so the JS engine doesn’t need to speculate when it optimizes the way it does with JavaScript.
executing often takes less time because there are fewer compiler tricks and gotchas that the developer needs to know to write consistently performant code, plus WebAssembly’s set of instructions are more ideal for machines.
garbage collection is not required since the memory is managed manually.
<!doctype html>
<title>WASM Collision Demo</title>
<body style="margin:0; overflow: hidden">
<canvas id="canvas" style="width: 100vw; height: 100vh; display:block;"></canvas>
<script>
fetch('https://cdn.rawgit.com/guybedford/wasm-intro/f61eb0d0/1-loading-wasm-fn/test.wasm')
.then(res => {
if (res.ok)
return res.arrayBuffer();
throw new Error(`Unable to fetch WASM.`);
})
.then(bytes => {
return WebAssembly.compile(bytes);
})
.then(module => {
return WebAssembly.instantiate(module);
})
.then(instance => {
window.wasmSqrt = instance.exports.sqrt;
});
</script>
<p>
for(i=0;i<10;i++){
var value = Math.random()*Math.random()*1000000;
console.time('wasmSqrt');window.wasmSqrt(value+0);console.timeEnd('wasmSqrt');
console.time('Mathsqrt');Math.sqrt(value+"0");console.timeEnd('Mathsqrt');
console.log('-----------')
}
</p>
</body>