Bun 性能优化 #

启动优化 #

使用预编译 #

bash
# 打包为可执行文件
bun build ./src/index.ts --compile --outfile app

减少依赖 #

bash
# 分析依赖
bun pm ls

运行时优化 #

使用 Bun 原生 API #

typescript
// 推荐:使用 Bun.file
const file = Bun.file("./data.txt");
const text = await file.text();

// 不推荐:使用 fs
import { readFile } from "fs/promises";
const text = await readFile("./data.txt", "utf-8");

使用 SQLite #

typescript
import { Database } from "bun:sqlite";

// 比 npm sqlite3 快得多
const db = new Database(":memory:");

HTTP 服务优化 #

启用压缩 #

typescript
Bun.serve({
  port: 3000,
  async fetch(request) {
    const response = new Response(largeData);
    response.headers.set("Content-Encoding", "gzip");
    return response;
  },
});

使用缓存 #

typescript
const cache = new Map<string, Response>();

Bun.serve({
  port: 3000,
  fetch(request) {
    const cached = cache.get(request.url);
    if (cached) return cached;
    
    const response = generateResponse();
    cache.set(request.url, response);
    return response;
  },
});

内存优化 #

流式处理 #

typescript
// 大文件流式处理
const file = Bun.file("./large-file.txt");
const stream = file.stream();

for await (const chunk of stream) {
  processChunk(chunk);
}

及时释放资源 #

typescript
// 关闭数据库连接
const db = new Database("./data.sqlite");
// 使用后关闭
db.close();

监控 #

内存使用 #

typescript
const used = process.memoryUsage();
console.log({
  rss: `${used.rss / 1024 / 1024} MB`,
  heapUsed: `${used.heapUsed / 1024 / 1024} MB`,
});

性能计时 #

typescript
console.time("operation");
// 操作
console.timeEnd("operation");

下一步 #

恭喜你完成了 Bun 文档的学习!现在你可以开始使用 Bun 构建高性能应用了。

最后更新:2026-03-29