workers-multi-lang
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseMulti-Language Workers Development
多语言Workers开发
Build Cloudflare Workers using Rust, Python, or WebAssembly for performance-critical operations.
使用Rust、Python或WebAssembly构建Cloudflare Workers,用于性能敏感型操作。
Language Comparison
语言对比
| Feature | JavaScript/TS | Rust | Python |
|---|---|---|---|
| Startup | Fast | Fastest (WASM) | Moderate |
| CPU Perf | Good | Excellent | Good |
| Memory | Higher | Lower | Higher |
| Bundle Size | Smaller | Medium | Larger |
| Type Safety | Optional (TS) | Strict | Optional |
| Best For | General apps | CPU-intensive | Data/ML |
| 特性 | JavaScript/TS | Rust | Python |
|---|---|---|---|
| 启动速度 | 快 | 最快(WASM) | 中等 |
| CPU性能 | 良好 | 极佳 | 良好 |
| 内存占用 | 较高 | 较低 | 较高 |
| 包体积 | 较小 | 中等 | 较大 |
| 类型安全性 | 可选(TS) | 严格 | 可选 |
| 适用场景 | 通用应用 | CPU密集型任务 | 数据/机器学习 |
Quick Decision
快速决策
Need maximum performance? → Rust/WASM
Heavy computation (crypto, image processing)? → Rust/WASM
Data processing, ML inference? → Python
General web apps? → JavaScript/TypeScriptNeed maximum performance? → Rust/WASM
Heavy computation (crypto, image processing)? → Rust/WASM
Data processing, ML inference? → Python
General web apps? → JavaScript/TypeScriptTop 10 Multi-Lang Errors
十大多语言开发常见错误
| Error | Language | Cause | Solution |
|---|---|---|---|
| Rust | Invalid WASM | Check wasm-pack build output |
| Rust | ESM/CJS mismatch | Use |
| Python | Missing dep | Add to pyproject.toml |
| All | Large WASM | Enable streaming instantiation |
| All | Long computation | Chunk processing |
| Rust | Dep conflict | Align versions in Cargo.toml |
| Rust | Panic in WASM | Add proper error handling |
| Rust | Missing export | Add |
| Python | Slow init | Minimize imports |
| All | Security | Add COOP/COEP headers |
| 错误 | 语言 | 原因 | 解决方案 |
|---|---|---|---|
| Rust | 无效WASM模块 | 检查wasm-pack构建输出 |
| Rust | ESM/CJS不兼容 | 使用 |
| Python | 依赖缺失 | 添加至pyproject.toml |
| 所有语言 | WASM模块过大 | 启用流式实例化 |
| 所有语言 | 计算耗时过长 | 拆分任务处理 |
| Rust | 依赖版本冲突 | 统一Cargo.toml中的版本 |
| Rust | WASM中发生panic | 添加完善的错误处理 |
| Rust | 缺少导出 | 添加 |
| Python | 初始化缓慢 | 减少导入依赖 |
| 所有语言 | 安全限制 | 添加COOP/COEP头 |
Rust Quick Start
Rust快速入门
bash
undefinedbash
undefinedInstall tools
Install tools
cargo install wasm-pack
cargo install wasm-pack
Create project
Create project
cargo new --lib my-worker
cd my-worker
cargo new --lib my-worker
cd my-worker
Add to Cargo.toml
Add to Cargo.toml
cat >> Cargo.toml << 'EOF'
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
worker = "0.3"
console_error_panic_hook = "0.1"
[profile.release]
opt-level = "s"
lto = true
EOF
```rust
// src/lib.rs
use worker::*;
#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
console_error_panic_hook::set_once();
Router::new()
.get("/", |_, _| Response::ok("Hello from Rust!"))
.get("/compute", |_, _| {
// CPU-intensive computation
let result = heavy_computation();
Response::ok(format!("Result: {}", result))
})
.run(req, env)
.await
}
fn heavy_computation() -> u64 {
(1..1_000_000).filter(|n| is_prime(*n)).count() as u64
}
fn is_prime(n: u64) -> bool {
if n < 2 { return false; }
(2..=(n as f64).sqrt() as u64).all(|i| n % i != 0)
}cat >> Cargo.toml << 'EOF'
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
worker = "0.3"
console_error_panic_hook = "0.1"
[profile.release]
opt-level = "s"
lto = true
EOF
```rust
// src/lib.rs
use worker::*;
#[event(fetch)]
async fn fetch(req: Request, env: Env, _ctx: Context) -> Result<Response> {
console_error_panic_hook::set_once();
Router::new()
.get("/", |_, _| Response::ok("Hello from Rust!"))
.get("/compute", |_, _| {
// CPU-intensive computation
let result = heavy_computation();
Response::ok(format!("Result: {}", result))
})
.run(req, env)
.await
}
fn heavy_computation() -> u64 {
(1..1_000_000).filter(|n| is_prime(*n)).count() as u64
}
fn is_prime(n: u64) -> bool {
if n < 2 { return false; }
(2..=(n as f64).sqrt() as u64).all(|i| n % i != 0)
}Python Quick Start (Workers for Platforms)
Python快速入门(Workers for Platforms)
toml
undefinedtoml
undefinedpyproject.toml
pyproject.toml
[project]
name = "my-worker"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = []
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
```python[project]
name = "my-worker"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = []
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
```pythonsrc/entry.py
src/entry.py
from js import Response, Headers
async def on_fetch(request, env):
url = request.url
if "/compute" in url:
result = heavy_computation()
return Response.new(f"Result: {result}")
return Response.new("Hello from Python!")def heavy_computation():
"""CPU-intensive computation"""
return sum(1 for n in range(2, 100000) if is_prime(n))
def is_prime(n):
if n < 2:
return False
return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
undefinedfrom js import Response, Headers
async def on_fetch(request, env):
url = request.url
if "/compute" in url:
result = heavy_computation()
return Response.new(f"Result: {result}")
return Response.new("Hello from Python!")def heavy_computation():
"""CPU-intensive computation"""
return sum(1 for n in range(2, 100000) if is_prime(n))
def is_prime(n):
if n < 2:
return False
return all(n % i != 0 for i in range(2, int(n**0.5) + 1))
undefinedWASM Module Integration
WASM模块集成
typescript
// Load and use WASM module in TypeScript Worker
import wasmModule from './pkg/my_lib_bg.wasm';
import { init, process_data } from './pkg/my_lib';
let wasmInstance: WebAssembly.Instance;
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Initialize WASM once
if (!wasmInstance) {
wasmInstance = await WebAssembly.instantiate(wasmModule);
init();
}
// Use WASM function
const result = process_data(inputData);
return Response.json({ result });
},
};typescript
// Load and use WASM module in TypeScript Worker
import wasmModule from './pkg/my_lib_bg.wasm';
import { init, process_data } from './pkg/my_lib';
let wasmInstance: WebAssembly.Instance;
export default {
async fetch(request: Request, env: Env): Promise<Response> {
// Initialize WASM once
if (!wasmInstance) {
wasmInstance = await WebAssembly.instantiate(wasmModule);
init();
}
// Use WASM function
const result = process_data(inputData);
return Response.json({ result });
},
};When to Load References
参考文档加载时机
| Reference | Load When |
|---|---|
| Building Workers with Rust/WASM |
| Using Python on Workers for Platforms |
| Integrating WASM modules in any Worker |
| 参考文档 | 加载场景 |
|---|---|
| 使用Rust/WASM构建Workers时 |
| 在Workers for Platforms上使用Python时 |
| 在任意Worker中集成WASM模块时 |
Performance Tips
性能优化技巧
- WASM Initialization: Cache instance, use streaming
- Memory: Use typed arrays for data transfer
- Bundle Size: Enable LTO, strip debug info
- Cold Starts: Keep WASM modules small
- Data Transfer: Minimize JS/WASM boundary crossings
- WASM初始化:缓存实例,使用流式加载
- 内存管理:使用类型化数组进行数据传输
- 包体积优化:启用LTO,移除调试信息
- 冷启动优化:保持WASM模块体积小巧
- 数据传输:减少JS与WASM之间的边界交互
See Also
相关链接
- - General optimization techniques
workers-performance - - Testing multi-language Workers
workers-testing - - Basic Workers setup
cloudflare-worker-base
- - 通用优化技巧
workers-performance - - 多语言Workers测试
workers-testing - - Workers基础配置
cloudflare-worker-base