JavaScript系列(80)--WebAssembly 基础入门
WebAssembly 基础入门 🚀
WebAssembly(简称Wasm)是一种低级的类汇编语言,它具有紧凑的二进制格式,能够以接近原生的性能在现代Web浏览器中运行。让我们深入了解这项革命性的技术。
WebAssembly 概述 🌟
💡 小知识:WebAssembly 是一种低级的、二进制的指令格式,专为堆栈式虚拟机设计。它被设计为C/C++等高级语言的编译目标,使得这些语言编写的程序能够在Web平台上以接近原生的速度运行。
基础概念与工具链 🛠️
// 1. 加载和实例化WebAssembly模块
async function loadWasmModule() {try {// 加载.wasm文件const response = await fetch('module.wasm');const bytes = await response.arrayBuffer();// 实例化模块const { instance } = await WebAssembly.instantiate(bytes);return instance.exports;} catch (error) {console.error('Failed to load WASM module:', error);throw error;}
}// 2. 使用工具链编译C++代码
/* example.cpp
#include <emscripten/bind.h>int fibonacci(int n) {if (n <= 1) return n;return fibonacci(n - 1) + fibonacci(n - 2);
}EMSCRIPTEN_BINDINGS(module) {emscripten::function("fibonacci", &fibonacci);
}
*/// 编译命令
// emcc example.cpp -o example.js -s WASM=1 -s EXPORTED_FUNCTIONS='["_fibonacci"]'// 3. 内存管理工具
class WasmMemoryManager {constructor(initialPages = 1) {this.memory = new WebAssembly.Memory({initial: initialPages,maximum: 100});this.buffer = new Uint8Array(this.memory.buffer);}allocate(size) {// 简单的内存分配const ptr = this.currentPtr;this.currentPtr += size;return ptr;}free(ptr) {// 内存释放(简化版)// 实际应用中需要更复杂的内存管理}writeString(str) {const bytes = new TextEncoder().encode(str);const ptr = this.allocate(bytes.length + 1);this.buffer.set(bytes, ptr);this.buffer[ptr + bytes.length] = 0; // null terminatorreturn ptr;}readString(ptr) {let end = ptr;while (this.buffer[end] !== 0) end++;return new TextDecoder().decode(this.buffer.slice(ptr, end));}
}
性能优化技术 ⚡
// 1. SIMD操作
/* C++代码示例
#include <emscripten/bind.h>
#include <emmintrin.h>void vectorAdd(float* a, float* b, float* result, int size) {for (int i = 0; i < size; i += 4) {__m128 va = _mm_load_ps(&a[i]);__m128 vb = _mm_load_ps(&b[i]);__m128 vr = _mm_add_ps(va, vb);_mm_store_ps(&result[i], vr);}
}
*/// 2. 内存对齐
class AlignedMemory {constructor() {this.memory = new WebAssembly.Memory({initial: 1,maximum: 10,shared: true});}allocateAligned(size, alignment = 16) {const ptr = (this.currentPtr + alignment - 1) & ~(alignment - 1);this.currentPtr = ptr + size;return ptr;}
}// 3. 并行计算
class ParallelComputation {constructor(wasmModule) {this.module = wasmModule;this.workers = [];}async initializeWorkers(count) {for (let i = 0; i < count; i++) {const worker = new Worker('wasm-worker.js');await this.initializeWorker(worker);this.workers.push(worker);}}async initializeWorker(worker) {const memory = new WebAssembly.Memory({initial: 1,maximum: 10,shared: true});worker.postMessage({type: 'init',memory,module: this.module});}computeParallel(data) {const chunkSize = Math.ceil(data.length / this.workers.length);return Promise.all(this.workers.map((worker, index) => {const start = index * chunkSize;const end = Math.min(start + chunkSize, data.length);return new Promise(resolve => {worker.onmessage = e => resolve(e.data);worker.postMessage({type: 'compute',data: data.slice(start, end)});});}));}
}
JavaScript集成 🔗
// 1. 函数导出与调用
class WasmModule {constructor() {this.exports = null;}async initialize() {const response = await fetch('module.wasm');const bytes = await response.arrayBuffer();const importObject = {env: {memory: new WebAssembly.Memory({ initial: 10 }),log: console.log,performance_now: performance.now.bind(performance)}};const { instance } = await WebAssembly.instantiate(bytes, importObject);this.exports = instance.exports;}callFunction(name, ...args) {if (!this.exports) {throw new Error('Module not initialized');}if (typeof this.exports[name] !== 'function') {throw new Error(`Function ${name} not found`);}return this.exports[name](...args);}
}// 2. 数据传输
class WasmDataTransfer {constructor(module) {this.module = module;this.memory = module.exports.memory;}writeArray(array) {const ptr = this.module.exports.allocate(array.length * 4);const view = new Float32Array(this.memory.buffer, ptr, array.length);view.set(array);return ptr;}readArray(ptr, length) {return new Float32Array(this.memory.buffer,ptr,length);}writeStruct(data) {// 假设结构体定义:struct Point { float x; float y; }const ptr = this.module.exports.allocate(8);const view = new DataView(this.memory.buffer, ptr);view.setFloat32(0, data.x, true);view.setFloat32(4, data.y, true);return ptr;}readStruct(ptr) {const view = new DataView(this.memory.buffer, ptr);return {x: view.getFloat32(0, true),y: view.getFloat32(4, true)};}
}// 3. 异步操作
class AsyncWasmOperations {constructor(module) {this.module = module;}async processLargeData(data) {const chunkSize = 1024 * 1024; // 1MBconst results = [];for (let i = 0; i < data.length; i += chunkSize) {const chunk = data.slice(i, i + chunkSize);// 让出主线程if (i % (chunkSize * 10) === 0) {await new Promise(resolve => setTimeout(resolve, 0));}const ptr = this.writeData(chunk);const result = this.module.exports.processChunk(ptr, chunk.length);results.push(result);}return results;}
}
实战应用示例 💼
// 1. 图像处理应用
class WasmImageProcessor {constructor() {this.module = null;this.initialize();}async initialize() {const module = await loadWasmModule('image_processor.wasm');this.module = module;}async processImage(imageData) {const { width, height, data } = imageData;// 分配内存const inputPtr = this.module.exports.allocate(data.length);const outputPtr = this.module.exports.allocate(data.length);// 复制数据new Uint8ClampedArray(this.module.exports.memory.buffer).set(data, inputPtr);// 处理图像this.module.exports.processImage(inputPtr,outputPtr,width,height);// 读取结果const result = new Uint8ClampedArray(this.module.exports.memory.buffer,outputPtr,data.length);return new ImageData(result, width, height);}
}// 2. 3D渲染引擎
class Wasm3DEngine {constructor() {this.module = null;this.memory = null;this.vertexBuffer = null;}async initialize() {const module = await loadWasmModule('3d_engine.wasm');this.module = module;this.memory = module.exports.memory;// 初始化顶点缓冲区this.vertexBuffer = new Float32Array(this.memory.buffer,module.exports.getVertexBufferPtr(),module.exports.getVertexBufferSize());}render(scene) {// 更新场景数据this.updateSceneData(scene);// 执行渲染this.module.exports.render();// 获取渲染结果return this.getFramebuffer();}
}// 3. 物理引擎
class WasmPhysicsEngine {constructor() {this.module = null;this.bodies = new Map();}async initialize() {const module = await loadWasmModule('physics.wasm');this.module = module;// 初始化物理世界this.module.exports.initWorld(9.81); // 重力加速度}addBody(body) {const ptr = this.module.exports.createBody(body.mass,body.position.x,body.position.y,body.position.z);this.bodies.set(body.id, ptr);}step(deltaTime) {this.module.exports.stepSimulation(deltaTime);// 更新所有物体的位置for (const [id, ptr] of this.bodies) {const pos = this.getBodyPosition(ptr);this.updateBodyPosition(id, pos);}}
}
调试与性能分析 🔍
// 1. 调试工具
class WasmDebugger {constructor(module) {this.module = module;this.breakpoints = new Set();}addBreakpoint(location) {this.breakpoints.add(location);}async startDebugging() {const debug = await WebAssembly.debug(this.module);debug.onBreakpoint = location => {console.log(`Breakpoint hit at ${location}`);this.inspectState();};}inspectMemory(ptr, size) {const view = new DataView(this.module.exports.memory.buffer, ptr, size);console.log('Memory at', ptr, ':', view);}
}// 2. 性能分析器
class WasmProfiler {constructor() {this.measurements = new Map();}startMeasure(name) {const start = performance.now();this.measurements.set(name, { start });}endMeasure(name) {const measurement = this.measurements.get(name);if (measurement) {measurement.end = performance.now();measurement.duration = measurement.end - measurement.start;}}getReport() {const report = {};for (const [name, data] of this.measurements) {report[name] = {duration: data.duration,timestamp: data.start};}return report;}
}// 3. 内存分析器
class WasmMemoryProfiler {constructor(module) {this.module = module;this.allocations = new Map();}trackAllocation(ptr, size) {this.allocations.set(ptr, {size,stack: new Error().stack});}trackDeallocation(ptr) {this.allocations.delete(ptr);}getMemoryUsage() {let total = 0;for (const { size } of this.allocations.values()) {total += size;}return total;}findMemoryLeaks() {return Array.from(this.allocations.entries()).filter(([_, data]) => {const age = performance.now() - data.timestamp;return age > 30000; // 30秒以上的分配});}
}
安全考虑 🔒
// 1. 内存隔离
class WasmSandbox {constructor() {this.memory = new WebAssembly.Memory({initial: 1,maximum: 10});this.importObject = {env: {memory: this.memory,// 安全的系统调用console_log: this.safeConsoleLog.bind(this)}};}safeConsoleLog(...args) {// 验证和清理参数const sanitizedArgs = args.map(arg => this.sanitizeValue(arg));console.log(...sanitizedArgs);}sanitizeValue(value) {// 实现值清理逻辑return String(value).replace(/[<>]/g, '');}
}// 2. 资源限制
class WasmResourceLimiter {constructor() {this.memoryLimit = 100 * 1024 * 1024; // 100MBthis.timeLimit = 5000; // 5秒}async executeWithLimits(wasmModule, functionName, ...args) {return new Promise((resolve, reject) => {const timeout = setTimeout(() => {reject(new Error('Execution time limit exceeded'));}, this.timeLimit);try {const result = wasmModule.exports[functionName](...args);clearTimeout(timeout);if (this.checkMemoryUsage(wasmModule)) {resolve(result);} else {reject(new Error('Memory limit exceeded'));}} catch (error) {clearTimeout(timeout);reject(error);}});}checkMemoryUsage(wasmModule) {const usage = wasmModule.exports.memory.buffer.byteLength;return usage <= this.memoryLimit;}
}// 3. 输入验证
class WasmInputValidator {static validateNumber(value) {if (typeof value !== 'number' || !isFinite(value)) {throw new Error('Invalid number input');}return value;}static validateArray(array, maxLength = 1000000) {if (!Array.isArray(array) || array.length > maxLength) {throw new Error('Invalid array input');}return array;}static validateString(str, maxLength = 1000) {if (typeof str !== 'string' || str.length > maxLength) {throw new Error('Invalid string input');}return str;}
}
结语 📝
WebAssembly为Web平台带来了接近原生的性能和更多的可能性。我们学习了:
- WebAssembly的基本概念和工具链
- 性能优化技术
- 与JavaScript的集成方式
- 实战应用场景
- 调试和性能分析
- 安全性考虑
💡 学习建议:
- 从简单的C/C++程序开始尝试编译到WebAssembly
- 理解内存模型和数据传输方式
- 注意性能优化和安全限制
- 合理处理JavaScript和WebAssembly的交互
- 使用适当的调试和分析工具
如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇
终身学习,共同成长。
咱们下一期见
💻
相关文章:
JavaScript系列(80)--WebAssembly 基础入门
WebAssembly 基础入门 🚀 WebAssembly(简称Wasm)是一种低级的类汇编语言,它具有紧凑的二进制格式,能够以接近原生的性能在现代Web浏览器中运行。让我们深入了解这项革命性的技术。 WebAssembly 概述 🌟 &…...
蓝桥杯刷题2.21|笔记
参考的是蓝桥云课十四天的那个题单,不知道我发这个有没有问题,如果有问题找我我立马删文。(参考蓝桥云课里边的题单,跟着大佬走,应该是没错滴,加油加油) 一、握手问题 #include <iostream&g…...
053 性能压测 单机锁 setnx
文章目录 性能压测-压力测试索引thymeleafnginx减少数据库查询(代码有bug)缓存 安全单机锁(防止缓存击穿)setnx pom.xml 性能压测-压力测试 1 响应时间(Response Time: RT):响应时间指用户从客…...
【天线】IFA天线知识点摘抄
MIFA天线的尺寸与性能关系 1,辐射效率 天线越小,辐射效率越低。唯一好处是减少PCB占用空间 2,带宽 一般MIFA天线在2.4G频段内的带宽:S11≤-10dB的范围为2.44GHz230MHz。较小的尺寸可能会限制带宽 3,增益 MIFA天线的…...
Mysql视图有什么作用?你是否使用过视图?
MySQL视图(View)是一种虚拟表,其内容由查询定义。视图并不实际存储数据,而是基于一个或多个表的查询结果生成。以下是关于MySQL视图的详细说明: 1. 视图的定义 概念:视图是一个虚拟表,其内容由…...
【vue项目如何利用event-stream实现文字流式输出效果】
引言 在现代 Web 应用中,实时数据展示是一个常见需求,例如聊天消息逐字显示、日志实时推送、股票行情更新等。传统的轮询或一次性数据加载方式无法满足这类场景的流畅体验,而 流式传输(Streaming) 技术则能实现数据的…...
微信问题总结(onpageshow ,popstate事件)
此坑描述 订单详情某按钮点击,通过window.location.href跳转到(外部)第三方链接后,回退后,在ios中生命周期和路由导航钩子都失效了,无法触发。 在安卓中无视此坑, 回退没有问题 解决 原因&am…...
【Gin-Web】Bluebell社区项目梳理3:社区相关接口开发
本文目录 一、接口详情1. 获取分类社区列表接口2. 根据id查询社区 二、值类型与引用类型 一、接口详情 跟社区有关的接口详情如下。 1. 获取分类社区列表接口 首先是Controller层,然后跳转到Logic层业务逻辑的开发。 这是Logic层,再做一次跳转&#…...
Unity 聊天气泡根据文本内容适配
第一步 拼接UI 1、对气泡图进行九宫图切割 2、设置底图pivot位置和对齐方式 pivot位置:(0,1) 对齐方式:左上对齐 3、设置文本pivot位置和对齐方式,并挂上布局组件 pivot设置和对齐方式和底图一样&#…...
对学习编程语言的一些理解
目录 一、代码运行的过程 二、跨平台的实现 1)C/C 2)C# 3)Java 三、总结 一、代码运行的过程 开发程序无论使用何种编程语言,至少都需要经历编码、编译、连接和运行这么4个过程,C语言是这样,Java语言…...
MySQL MHA 部署全攻略:从零搭建高可用数据库架构
文章目录 1.MHA介绍2.MHA组件介绍3.集群规划4.服务器初始化5.MySQL集群部署5.1 安装MySQL集群5.2 配置一主两从5.3 测试MySQL主从5.4 赋予MHA用户连接权限 6.安装MHA环境6.1 安装MHA Node6.2 安装MHA Manager 7.配置MHA环境8.MySQL MHA高可用集群测试8.1 通过VIP连接MySQL8.2模…...
windows怎样查看系统信息(处理器等)
首先打开命令行工具 win R 输入 cmd, 输入 msinfo32 ,然后回车 这个页面就可以看到 电脑的锐龙版就是 AMD 芯片 酷睿版就是 intel 芯片...
007 HBuilderX提示IDE service port disabled. To use CLI Call, open IDE
描述 微信小程序 工具的服务端口已关闭 解决方案 在HBuider的菜单“运行”选择“运行到小程序模拟器-微信开发者工具”时,步骤如图: 提示:IDE service port disabled. To use CLI Call, open IDE -> Settings -> Security Settings,…...
计算机网络之TCP的可靠传输
上一篇内容可能比较多,显得比较杂乱,这一篇简单总结一下TCP是靠什么实现可靠传输的吧。 校验和 TCP是端到端的传输,由发送方计算校验和,接收方进行验证,目的是为了验证TCP首部和数据在发送过程中没有任何改动&#x…...
Python爬虫系列教程之第十四篇:爬虫项目部署、调度与监控系统
大家好,欢迎继续关注本系列爬虫教程! 在前面的文章中,我们已经详细讲解了如何构建爬虫、如何处理反爬、如何实现分布式爬虫以及如何使用 Scrapy 框架开发高效的爬虫项目。随着项目规模的不断扩大,如何将爬虫项目稳定部署到生产环境…...
线程与进程的深入解析及 Linux 线程编程
在操作系统中,进程和线程是进行并发执行的两种基本单位。理解它们的区别和各自的特点,能够帮助开发者更好地进行多任务编程,提高程序的并发性能。本文将探讨进程和线程的基础概念,及其在 Linux 系统中的实现方式,并介绍…...
在ubuntu上用Python的openpyxl模块操作Excel的案例
文章目录 安装模块读取Excel数据库取数匹配数据和更新Excel数据 在Ubuntu系统的环境下基本职能借助Python的openpyxl模块实现对Excel数据的操作。 安装模块 本次需要用到的模块需要提前安装(如果没有的话) pip3 install openpyxl pip3 install pymysql在操作前,需…...
【OS安装与使用】part6-ubuntu 22.04+CUDA 12.4运行MARL算法(多智能体强化学习)
文章目录 一、待解决问题1.1 问题描述1.2 解决方法 二、方法详述2.1 必要说明2.2 应用步骤2.2.1 下载源码并安装2.2.2 安装缺失的依赖项2.2.3 训练执行MAPPO算法实例 三、疑问四、总结 一、待解决问题 1.1 问题描述 已配置好基础的运行环境,尝试运行MARL算法。 1…...
【Python爬虫(35)】解锁Python多进程爬虫:高效数据抓取秘籍
【Python爬虫】专栏简介:本专栏是 Python 爬虫领域的集大成之作,共 100 章节。从 Python 基础语法、爬虫入门知识讲起,深入探讨反爬虫、多线程、分布式等进阶技术。以大量实例为支撑,覆盖网页、图片、音频等各类数据爬取ÿ…...
HarmonyOS 开发套件 介绍 ——上篇
HarmonyOS 开发套件 介绍 ——上篇 在当今科技飞速发展的时代,操作系统作为智能设备的核心,其重要性不言而喻。而HarmonyOS,作为华为推出的全新操作系统,正以其独特的魅力和强大的功能,吸引着越来越多的开发者和用户的…...
大话软工笔记—需求分析概述
需求分析,就是要对需求调研收集到的资料信息逐个地进行拆分、研究,从大量的不确定“需求”中确定出哪些需求最终要转换为确定的“功能需求”。 需求分析的作用非常重要,后续设计的依据主要来自于需求分析的成果,包括: 项目的目的…...
线程同步:确保多线程程序的安全与高效!
全文目录: 开篇语前序前言第一部分:线程同步的概念与问题1.1 线程同步的概念1.2 线程同步的问题1.3 线程同步的解决方案 第二部分:synchronized关键字的使用2.1 使用 synchronized修饰方法2.2 使用 synchronized修饰代码块 第三部分ÿ…...
Python实现prophet 理论及参数优化
文章目录 Prophet理论及模型参数介绍Python代码完整实现prophet 添加外部数据进行模型优化 之前初步学习prophet的时候,写过一篇简单实现,后期随着对该模型的深入研究,本次记录涉及到prophet 的公式以及参数调优,从公式可以更直观…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...
浅谈不同二分算法的查找情况
二分算法原理比较简单,但是实际的算法模板却有很多,这一切都源于二分查找问题中的复杂情况和二分算法的边界处理,以下是博主对一些二分算法查找的情况分析。 需要说明的是,以下二分算法都是基于有序序列为升序有序的情况…...
vue3+vite项目中使用.env文件环境变量方法
vue3vite项目中使用.env文件环境变量方法 .env文件作用命名规则常用的配置项示例使用方法注意事项在vite.config.js文件中读取环境变量方法 .env文件作用 .env 文件用于定义环境变量,这些变量可以在项目中通过 import.meta.env 进行访问。Vite 会自动加载这些环境变…...
Swagger和OpenApi的前世今生
Swagger与OpenAPI的关系演进是API标准化进程中的重要篇章,二者共同塑造了现代RESTful API的开发范式。 本期就扒一扒其技术演进的关键节点与核心逻辑: 🔄 一、起源与初创期:Swagger的诞生(2010-2014) 核心…...
Web 架构之 CDN 加速原理与落地实践
文章目录 一、思维导图二、正文内容(一)CDN 基础概念1. 定义2. 组成部分 (二)CDN 加速原理1. 请求路由2. 内容缓存3. 内容更新 (三)CDN 落地实践1. 选择 CDN 服务商2. 配置 CDN3. 集成到 Web 架构 …...
USB Over IP专用硬件的5个特点
USB over IP技术通过将USB协议数据封装在标准TCP/IP网络数据包中,从根本上改变了USB连接。这允许客户端通过局域网或广域网远程访问和控制物理连接到服务器的USB设备(如专用硬件设备),从而消除了直接物理连接的需要。USB over IP的…...
基于Java+MySQL实现(GUI)客户管理系统
客户资料管理系统的设计与实现 第一章 需求分析 1.1 需求总体介绍 本项目为了方便维护客户信息为了方便维护客户信息,对客户进行统一管理,可以把所有客户信息录入系统,进行维护和统计功能。可通过文件的方式保存相关录入数据,对…...
