为什么Bun查询数据库接口响应比Rust还快

63 阅读1分钟

bun的响应速度比rust快,表里三十多万条数据,我直接全查了。用的分别是axum和hono,都是最简单写法。

app.get("/", async (c) => {
  // ===== 1. 查询计时 =====
  const t1 = Date.now();
  const weightRows = await db.execute(sql`
      SELECT *
      FROM "weight"
      ORDER BY "uuid" ASC
    `);
  const queryTime = Date.now() - t1;
  // ===== 2. 纯序列化计时(手动 JSON.stringify) =====
  const t2 = Date.now();
  const jsonString = JSON.stringify(weightRows);
  const serializeTime = Date.now() - t2;

  console.log(
    `[性能] 查询 ${queryTime}ms | 序列化 ${serializeTime}ms | 行数 ${weightRows.length}`,
  );

  // ===== 3. 返回手动序列化结果,避免 c.json 二次序列化 =====
  return c.body(jsonString, 200, {
    "Content-Type": "application/json; charset=utf-8",
    // 可选:告诉客户端内容长度,帮助进度条
    "Content-Length": Buffer.byteLength(jsonString).toString(),
  });
});


async fn root(State(state): State<SharedState>) -> impl IntoResponse {
    let start = Instant::now();

    let rows = sqlx::query_as::<_, WeightRawRow>("SELECT * FROM weight ORDER BY uuid")
        .fetch_all(&state.pool)
        .await
        .unwrap();

    let query_time = start.elapsed();
    println!(
        "查询完成: {}ms, 行数: {}",
        query_time.as_millis(),
        rows.len()
    );

    let serialize_start = Instant::now();
    let json_bytes = serde_json::to_vec(&rows).unwrap();
    let serialize_time = serialize_start.elapsed();
    println!("序列化耗时: {}ms", serialize_time.as_millis());

    let total_time = start.elapsed();
    println!("总耗时: {}ms", total_time.as_millis());

    Response::builder()
        .header("content-type", "application/json")
        .body(Body::from(json_bytes))
        .unwrap()
}