You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constKoa=require('koa')constpath=require('path')conststatic=require('koa-static')constapp=newKoa()conststaticPath='./../../'app.use(static(path.join(__dirname,staticPath)))app.listen(3000,()=>{console.log('[INFO]: server starting at port 3000');console.log('open: http://127.0.0.1:3000/example/browser/index.html')})
前言
前段时间开发图像处理工具Pictool后,遇到高频的计算瓶颈。在寻找高频计算的前端能力解决方案过程中,入门学习了一下 WebAssembly 在前端中的应用。入门的过程中踩了不少坑,例如使用
AssemblyScript
开发wasm
时候,发现npm
包assemblyscript
已经不维护了,需要自己人工添加成从Github
仓库引用assemblyscript
的npm
模块。同时网上很多教程已经有点不同步,很多按照教程步骤后实现的代码跑不起来。最后参考原有网上的教程,一步步踩坑,实现了demo,同时也写下这篇文章作为笔记!
WebAssembly
什么是 WebAssembly
WebAssembly 优势
在前端主要的优势有
WebAssembly 前端能力现状
什么是 AssemblyScript
AssemblyScript
是TypeScript
的一个子集TypeScript
语法编写功能编译成wasm
,对前端来说比较友好。快速开始
demo源码地址
如果想更快速尝试,可以直接去该 demo 仓库获取源码使用。
https://github.com/chenshenhai/assemblyscript-demo
安装 AssemblyScript
由于
AssemblyScript
的npm
官方模块已经停止维护,所以AssemblyScript
的模块需要从Github
来源安装。在
package.json
的依赖加入AssemblyScript
模块的Github
来源./package.json
再执行
npm install
从Github
下载该模块到本地node_module
中编写功能代码
编写一个
斐波那契数列
函数在 demo 的目录
./src/index.ts
中编译
在
package.json
编写编译脚本./package.json
在项目根目录开始执行编译
后面会在
./dist/
目录下产生编译后的几种wasm
文件格式Node.js 使用
在
./example/node/module.js
文件中,封装wasm
的CommonJS
使用模块Node.js 使用
执行 Node.js 的
wasm
引用输出结果会是
浏览器使用
在
./example/browser/
目录下部署浏览器访问的服务临时浏览器可访问的服务,这里用
koa
来搭建服务具体实现在
./example/browser/server.js
文件中浏览器使用
wasm
模块具体实现在
./example/browser/demo.js
文件中实现访问页面在
./example/browser/index.html
中启动服务
浏览器访问页面
http://127.0.0.1:3000/example/browser/index.html
浏览器会出现结果
性能测试
Node.js 对比测试
测试结果
833 ms
597 ms
斐波那契数列
比 js 执行快了接近30%
浏览器对比测试
测试结果
884 ms
612 ms
斐波那契数列
比 js 执行快了也是接近30%
从上述 Node.js 和 Chrome 环境下运行
wasm
和 原生js
的对比中,wasm
的在高频计算的场景下,耗时的确是比原生js
低,同时都是接近30%
的计算性能提升。参考资料
The text was updated successfully, but these errors were encountered: