[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"public:announcements":3,"post:detail:post-11-WebAssembl:zh":4,"public:navigations:zh":58,"footer:categories:zh":105},[],{"id":5,"title":6,"subtitle":7,"slug":8,"source":9,"source_url":7,"audio":7,"video":7,"video_url":7,"content":10,"excerpt":11,"cover_image":7,"author":12,"category":16,"tags":24,"status":50,"visibility":51,"password":7,"views":52,"likes_count":23,"is_pinned":53,"allow_comments":30,"comments_count":54,"is_password_protected":53,"meta_title":6,"meta_description":11,"meta_keywords":55,"created_at":56,"published_at":56,"updated_at":57,"reading_time":13},11,"WebAssembly 入门：Rust 编译 WASM + JS 调用",null,"post-11-WebAssembl","原创","# WebAssembly 入门：Rust 编译 WASM + JS 调用\n\n前端遇到图像\u002F矩阵\u002F密码学等 CPU 密集任务时，JS 性能成瓶颈。WebAssembly 让 Rust 代码编译为接近原生速度的字节码。\n\n## 工具链与基础绑定\n\n安装 wasm-pack 后，用 #[wasm_bindgen] 宏把 Rust 函数导出为 JS 可调用形式。复杂结构用 serde + serde_wasm_bindgen 序列化跨语言传递。\n\n```rust\n```rust\nuse wasm_bindgen::prelude::*;\nuse serde::{Serialize, Deserialize};\nuse web_sys::console;\n\n#[derive(Serialize, Deserialize)]\npub struct MatrixResult { rows: usize, cols: usize, data: Vec\u003Cf64>, compute_ms: f64 }\n\n#[wasm_bindgen(start)]\npub fn init() {\n    console_error_panic_hook::set_once();\n    console::log_1(&\"[WASM] Matrix module loaded\".into());\n}\n\n#[wasm_bindgen]\npub fn matrix_multiply(a_ptr: *mut f64, a_rows: usize, a_cols: usize, b_ptr: *mut f64, b_cols: usize) -> JsValue {\n    use std::time::Instant;\n    let t0 = Instant::now();\n    let a = unsafe { std::slice::from_raw_parts(a_ptr, a_rows * a_cols) };\n    let b = unsafe { std::slice::from_raw_parts(b_ptr, a_cols * b_cols) };\n    let mut c = vec![0.0f64; a_rows * b_cols];\n    for i in 0..a_rows {\n        for k in 0..a_cols {\n            let aik = a[i * a_cols + k];\n            let rb = &b[k * b_cols..(k + 1) * b_cols];\n            let rc = &mut c[i * b_cols..(i + 1) * b_cols];\n            for j in 0..b_cols { rc[j] += aik * rb[j]; }\n        }\n    }\n    let r = MatrixResult { rows: a_rows, cols: b_cols, data: c, compute_ms: t0.elapsed().as_secs_f64() * 1000.0 };\n    serde_wasm_bindgen::to_value(&r).unwrap()\n}\n\n#[wasm_bindgen]\npub fn fibonacci_iter(n: u32) -> u64 {\n    if n \u003C= 1 { return n as u64; }\n    let (mut prev, mut curr) = (0u64, 1u64);\n    for _ in 2..=n { let next = prev.saturating_add(curr); prev = curr; curr = next; }\n    curr\n}\n\n#[wasm_bindgen(js_name = \"allocateFloat64Array\")]\npub fn allocate_f64(len: usize) -> *mut f64 {\n    let mut v = Vec::with_capacity(len);\n    let p = v.as_mut_ptr();\n    std::mem::forget(v);\n    p\n}\n```\n```\n\n## JS 调用与内存共享\n\nWASM 内存是共享 ArrayBuffer，通过 TypedArray 视图直接读写比参数序列化快 10-100 倍。大数据时直接分配内存给 JS 端填充，再传指针和尺寸给 WASM。\n\n| 对比项 | 纯 JS | WASM (Rust) | 加速倍数 | 适用场景 |\n|--------|------|------------|---------|---------|\n| 矩阵乘法 1024x1024 | ~1800ms | ~85ms | ~21x | 3D\u002F游戏\u002FAI推理 |\n| Fibonacci(n=40) | ~980ms | ~8ms | ~120x | 数学计算 |\n| SHA-256 1MB | ~42ms | ~6ms | ~7x | 密码学\u002F校验 |\n\n## 最佳实践\n\n适合计算密集型循环，不要做 DOM 操作。优先 TypedArray 共享内存而非大对象参数，发布构建用 wasm-opt 优化体积。","从零搭建 Rust → WebAssembly 开发流程：wasm-pack 工具链、wasm-bindgen 类型绑定、JavaScript 同步\u002F异步调用 WASM 函数、内存共享与 TypedArray 传递大数据，适合计算密集型任务移植到浏览器端。",{"id":13,"username":14,"nickname":14,"avatar":7,"cover_image":7,"bio":7,"website":7,"github":7,"avatar_source":7,"resolved_avatar_url":7,"title":7,"created_at":15},1,"Choyeon","2026-09-30T18:09:53.330367Z",{"id":13,"name":17,"slug":18,"description":19,"icon":20,"color":21,"cover_image":7,"created_at":22,"post_count":23},"技术","technology","前沿技术探索与深度分析，涵盖编程语言、框架、架构设计等核心领域","heroicons:cog-6-tooth","#6366f1","2026-09-30T18:09:53.633610Z",0,[25,32,38,44],{"id":26,"name":27,"slug":28,"color":29,"icon":7,"is_active":30,"created_at":31,"post_count":23},7,"JavaScript","javascript","#f7df1e",true,"2026-09-30T18:09:53.683194Z",{"id":33,"name":34,"slug":35,"color":36,"icon":7,"is_active":30,"created_at":37,"post_count":23},15,"性能优化","performance","#f97316","2026-09-30T18:09:53.707190Z",{"id":39,"name":40,"slug":41,"color":42,"icon":7,"is_active":30,"created_at":43,"post_count":23},18,"WebAssembly","webassembly","#654ff0","2026-09-30T18:09:53.715731Z",{"id":45,"name":46,"slug":47,"color":48,"icon":7,"is_active":30,"created_at":49,"post_count":23},21,"Rust","rust","#dea584","2026-09-30T18:09:53.723993Z","published","public",504,false,6,"WebAssembly,Rust,JavaScript,性能优化","2026-08-31T23:09:53.733462Z","2026-09-30T21:00:49.364299Z",[59,68,75,83,91,99],{"id":13,"title":60,"url":65,"icon":7,"parent_id":7,"location":66,"order":13,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},{"zh":61,"en":62,"ja":63,"zh_TW":64},"首页","Home","ホーム","首頁","\u002F","header","2026-09-30T18:09:54.251095Z",{"id":69,"title":70,"url":74,"icon":7,"parent_id":7,"location":66,"order":69,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},2,{"zh":71,"en":72,"ja":73,"zh_TW":71},"文章","Posts","記事","\u002Fposts",{"id":76,"title":77,"url":82,"icon":7,"parent_id":7,"location":66,"order":76,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},3,{"zh":78,"en":79,"ja":80,"zh_TW":81},"分类","Categories","カテゴリー","分類","\u002Fcategories",{"id":84,"title":85,"url":90,"icon":7,"parent_id":7,"location":66,"order":84,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},4,{"zh":86,"en":87,"ja":88,"zh_TW":89},"标签","Tags","タグ","標籤","\u002Ftags",{"id":92,"title":93,"url":98,"icon":7,"parent_id":7,"location":66,"order":92,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},5,{"zh":94,"en":95,"ja":96,"zh_TW":97},"关于","About","概要","關於","\u002Fpage\u002Fabout",{"id":54,"title":100,"url":104,"icon":7,"parent_id":7,"location":66,"order":54,"is_active":30,"target_blank":53,"created_at":67,"updated_at":7},{"zh":101,"en":102,"ja":103,"zh_TW":101},"留言板","Guestbook","ゲストブック","\u002Fpage\u002Fguestbook",[106,116,130,144,159,174,189,203],{"id":13,"name":107,"slug":18,"description":111,"icon":20,"color":21,"cover_image":7,"created_at":22,"post_count":115},{"en":108,"ja":109,"zh":17,"zh_Hant":110},"Technology","テクノロジー","技術",{"en":112,"ja":113,"zh":19,"zh_Hant":114},"Cutting-edge technology exploration and in-depth analysis covering programming languages, frameworks, and architecture design","プログラミング言語、フレームワーク、アーキテクチャ設計を含む先端技術の探究","前沿技術探索與深度分析，涵蓋編程語言、框架、架構設計等核心領域",8,{"id":69,"name":117,"slug":121,"description":122,"icon":127,"color":128,"cover_image":7,"created_at":129,"post_count":54},{"en":118,"ja":119,"zh":120,"zh_Hant":120},"Tutorial","チュートリアル","教程","tutorial",{"en":123,"ja":124,"zh":125,"zh_Hant":126},"Hands-on tutorials from scratch with clear steps and complete code for developers at all levels","ゼロから始める実践的なチュートリアル。明確な手順と完全なコードで、全てのレベルの開発者に最適","从零开始的实战教程，步骤清晰，代码完整，适合各阶段开发者学习","從零開始的實戰教程，步驟清晰，代碼完整，適合各階段開發者學習","heroicons:academic-cap","#10b981","2026-09-30T18:09:53.641581Z",{"id":76,"name":131,"slug":135,"description":136,"icon":141,"color":142,"cover_image":7,"created_at":143,"post_count":26},{"en":132,"ja":133,"zh":134,"zh_Hant":134},"Frontend","フロントエンド","前端","frontend",{"en":137,"ja":138,"zh":139,"zh_Hant":140},"Full coverage of web frontend development including Vue, React, new CSS features, and performance optimization","Vue、React、CSSの新機能やパフォーマンス最適化を含むWebフロントエンド開発の全領域","Web前端开发全栈覆盖，包括Vue、React、CSS新特性及性能优化等话题","Web前端開發全棧覆蓋，包括Vue、React、CSS新特性及性能優化等話題","heroicons:computer-desktop","#ec4899","2026-09-30T18:09:53.644838Z",{"id":84,"name":145,"slug":150,"description":151,"icon":156,"color":157,"cover_image":7,"created_at":158,"post_count":76},{"en":146,"ja":147,"zh":148,"zh_Hant":149},"Backend","バックエンド","后端","後端","backend",{"en":152,"ja":153,"zh":154,"zh_Hant":155},"Server-side development best practices including API design, database optimization, and microservices architecture","API設計、データベース最適化、マイクロサービスアーキテクチャを含むサーバーサイド開発の実践","服务端开发实战经验，API设计、数据库优化、微服务架构等深度内容","服務端開發實戰經驗，API設計、數據庫優化、微服務架構等深度內容","heroicons:server-stack","#f59e0b","2026-09-30T18:09:53.647836Z",{"id":92,"name":160,"slug":165,"description":166,"icon":171,"color":172,"cover_image":7,"created_at":173,"post_count":23},{"en":161,"ja":162,"zh":163,"zh_Hant":164},"Fullstack","フルスタック","全栈","全棧","fullstack",{"en":167,"ja":168,"zh":169,"zh_Hant":170},"End-to-end development guides covering the full project lifecycle and technology stack selection","フロントエンドからバックエンドまでの開発プロセス全体をカバーするガイド","从前端到后端的全流程开发指南，覆盖完整项目生命周期与技术选型","從前端到後端的全流程開發指南，覆蓋完整項目生命週期與技術選型","heroicons:swatch","#8b5cf6","2026-09-30T18:09:53.650513Z",{"id":54,"name":175,"slug":180,"description":181,"icon":186,"color":187,"cover_image":7,"created_at":188,"post_count":84},{"en":176,"ja":177,"zh":178,"zh_Hant":179},"Essays","エッセイ","随笔","隨筆","essays",{"en":182,"ja":183,"zh":184,"zh_Hant":185},"Technical reflections and development insights recording the programmer's growth journey","プログラマーの成長の軌跡を記録する技術的考察と開発の洞察","技术思考与开发心得分享，记录程序员成长路上的点滴感悟","技術思考與開發心得分享，記錄程序員成長路上的點滴感悟","heroicons:pencil-square","#f43f5e","2026-09-30T18:09:53.653105Z",{"id":26,"name":190,"slug":194,"description":195,"icon":200,"color":201,"cover_image":7,"created_at":202,"post_count":84},{"en":191,"ja":192,"zh":193,"zh_Hant":193},"Tools","ツール","工具","tools",{"en":196,"ja":197,"zh":198,"zh_Hant":199},"Development toolchain and productivity tool recommendations to supercharge your development experience","開発効率を飛躍的に向上させるツールチェーンと生産性ツールの推奨","开发工具链与效率提升利器推荐，让你的开发体验如虎添翼","開發工具鏈與效率提升利器推薦，讓你的開發體驗如虎添翼","heroicons:wrench-screwdriver","#06b6d4","2026-09-30T18:09:53.655605Z",{"id":115,"name":204,"slug":209,"description":210,"icon":215,"color":216,"cover_image":7,"created_at":217,"post_count":23},{"en":205,"ja":206,"zh":207,"zh_Hant":208},"Translation","翻訳","翻译","翻譯","translation",{"en":211,"ja":212,"zh":213,"zh_Hant":214},"Curated translations of high-quality foreign technical articles to keep up with international trends","国際的な技術トレンドを追うための厳選された海外技術記事の翻訳","优质外文技术文章精选翻译，紧跟国际技术前沿动态","優質外文技術文章精選翻譯，緊跟國際技術前沿動態","heroicons:language","#84cc16","2026-09-30T18:09:53.658041Z"]