[Bun] Bun notes

Bun 课堂笔记

对比 Node.js Bun
语言 C++ Zig
JS 引擎 V8 JSCore

Zig:https://ziglang.org/

关于 V8 和 JSCore 各自有不同的架构和优化策略:

  • JSC 优先考虑的是更快的启动时间和更少的内存占用,执行时间会稍微久一下
  • V8 优先考虑快速执行,同时进行运行时的优化,但是 V8 会导致更多的内存占用

因此 Bun 这个运行时的特点就是速度很快,特别是启动速度,基本比 Node.js 快 3-4 倍。

Bun 官网:https://bun.sh/

首先第一步需要安装 Bun,直接使用 npm 全局安装即可:

npm install -g bun

安装完成之后通过 bun -v 可以查看版本。

包管理器

Bun 除了是一个 JavaScript 运行时,同时还是一个包管理器。

回顾在 Node.js 环境中,流行的包管理器:

  • npm(官方)
  • yarn
  • pnpm

但是 Bun 中,天然就自带包管理器。

测试运行器

Bun 同时还自带测试运行器。Bun 的内部有一个内置的测试模块 bun:test
如果你熟悉 Jest/Vitest,那么你可以无缝的迁移过来,零学习成本。

总结

Bun 首先是一个 JS 的运行时,但是不仅仅是运行时,还是一个全能的工具包,其中包含了:

  • 包管理器
  • 测试运行器
  • 构建工具
  • 转译器(天生支持 ts)

除此之外,Bun 还有相当多的非常实用的特性:

  • 天生支持 ts 以及 JSX
  • ESM 和 CommonJS 兼容
  • 内置 WebAPI
  • 能够使用顶层 await
  • 热更新

Elysia

Elysia 是一个基于 Bun 运行时的 Web 框架。
官网地址:https://elysiajs.com/

Performance

// node-server.js
import http from "http";
const hostname = "localhost";
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader("Content-Type", "text/plain");
  res.end("Hello World By Node.js");
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/ by Node.js`);
});
// bun-server.js
// 在 Bun 这个运行时里面,内置了一个全局的对象叫做 Bun
// 这个对象里面有一些全局的方法,比如说 Bun.serve
// 该方法就是创建一个服务器

const server = Bun.serve({
  port: 3001,
  fetch() {
    return new Response("Hello World!");
  },
});

console.log(`Server is running at http://localhost:${server.port} by Bun`);
// test_node.js
import fetch from "node-fetch";

let count = 1000; // 要发送的请求数量,初始化为 1000
const start = Date.now(); // 开始时间
let err_count = 0; // 错误数量

async function runTest() {
  while (count > 0) {
    try {
      const res = await fetch("http://localhost:3000");
      await res.text();
      count--;
    } catch (err) {
      err_count++;
    }
  }

  const end = Date.now(); // 结束时间

  console.log(`花费时间为:${end - start}ms`);
  console.log(`错误数量为:${err_count}`);
}

runTest();
// test_bun.js
import fetch from "node-fetch";

let count = 1000; // 要发送的请求数量,初始化为 1000
const start = Date.now(); // 开始时间
let err_count = 0; // 错误数量

async function runTest() {
  while (count > 0) {
    try {
      const res = await fetch("http://localhost:3001");
      await res.text();
      count--;
    } catch (err) {
      err_count++;
    }
  }

  const end = Date.now(); // 结束时间

  console.log(`花费时间为:${end - start}ms`);
  console.log(`错误数量为:${err_count}`);
}

runTest();

Result

posted @ 2024-11-24 16:20  Zhentiw  阅读(112)  评论(0)    收藏  举报