示例工程 27-framework-comparison

27-framework-comparison/app/src/lib/bench.ts

typescript · 4.9 KB

import { createElement, useState, version as reactVersion } from "react";
import { flushSync } from "react-dom";
import { createRoot } from "react-dom/client";
import { createApp, h, nextTick, ref, version as vueVersion } from "vue";
import { mount, tick, unmount } from "svelte";
import sveltePkg from "svelte/package.json";
import BenchList from "../components/BenchList.svelte";
import { median, round } from "./stats";

export type BenchRow = { id: number; text: string };

export type FrameworkResult = {
  id: "react" | "vue" | "svelte";
  label: string;
  mountMs: number;
  updateMs: number;
  rows: number;
  runs: number;
  updates: number;
  version: string;
};

export type BenchmarkReport = {
  rows: number;
  runs: number;
  updates: number;
  results: FrameworkResult[];
};

const ROWS = 200;
const RUNS = 8;
const UPDATES = 25;

let reactSetCount: ((value: number) => void) | null = null;

function ReactList({ rows }: { rows: BenchRow[] }) {
  const [count, setCount] = useState(0);
  reactSetCount = setCount;
  return createElement(
    "ul",
    { className: "bench-list" },
    rows.map((row) =>
      createElement("li", { key: row.id }, `${row.text} ${count}`),
    ),
  );
}

function makeRows(): BenchRow[] {
  return Array.from({ length: ROWS }, (_, index) => ({
    id: index + 1,
    text: `row ${index + 1}`,
  }));
}

function container(): HTMLDivElement {
  const element = document.createElement("div");
  element.style.position = "fixed";
  element.style.left = "-10000px";
  element.style.top = "0";
  document.body.append(element);
  return element;
}

async function benchReact(rows: BenchRow[]): Promise<FrameworkResult> {
  const mounts: number[] = [];
  const updates: number[] = [];
  for (let run = 0; run <= RUNS; run += 1) {
    const target = container();
    const root = createRoot(target);
    const mountStart = performance.now();
    flushSync(() => {
      root.render(createElement(ReactList, { rows }));
    });
    const mountMs = performance.now() - mountStart;

    const updateStart = performance.now();
    for (let index = 0; index < UPDATES; index += 1) {
      flushSync(() => {
        reactSetCount?.(index);
      });
    }
    const updateMs = performance.now() - updateStart;

    root.unmount();
    target.remove();
    if (run > 0) {
      mounts.push(mountMs);
      updates.push(updateMs);
    }
  }
  return {
    id: "react",
    label: "React 19",
    mountMs: round(median(mounts)),
    updateMs: round(median(updates)),
    rows: ROWS,
    runs: RUNS,
    updates: UPDATES,
    version: reactVersion,
  };
}

async function benchVue(rows: BenchRow[]): Promise<FrameworkResult> {
  const mounts: number[] = [];
  const updates: number[] = [];
  for (let run = 0; run <= RUNS; run += 1) {
    const target = container();
    const count = ref(0);
    const app = createApp({
      render: () =>
        h(
          "ul",
          { class: "bench-list" },
          rows.map((row) =>
            h("li", { key: row.id }, `${row.text} ${count.value}`),
          ),
        ),
    });
    const mountStart = performance.now();
    app.mount(target);
    const mountMs = performance.now() - mountStart;

    const updateStart = performance.now();
    for (let index = 0; index < UPDATES; index += 1) {
      count.value = index;
      await nextTick();
    }
    const updateMs = performance.now() - updateStart;

    app.unmount();
    target.remove();
    if (run > 0) {
      mounts.push(mountMs);
      updates.push(updateMs);
    }
  }
  return {
    id: "vue",
    label: "Vue 3",
    mountMs: round(median(mounts)),
    updateMs: round(median(updates)),
    rows: ROWS,
    runs: RUNS,
    updates: UPDATES,
    version: vueVersion,
  };
}

async function benchSvelte(rows: BenchRow[]): Promise<FrameworkResult> {
  const mounts: number[] = [];
  const updates: number[] = [];
  for (let run = 0; run <= RUNS; run += 1) {
    const target = container();
    const mountStart = performance.now();
    const instance = mount(BenchList, {
      target,
      props: { rows },
    }) as unknown as { bump: (value: number) => void };
    const mountMs = performance.now() - mountStart;

    const updateStart = performance.now();
    for (let index = 0; index < UPDATES; index += 1) {
      instance.bump(index);
      await tick();
    }
    const updateMs = performance.now() - updateStart;

    unmount(instance as unknown as Parameters<typeof unmount>[0]);
    target.remove();
    if (run > 0) {
      mounts.push(mountMs);
      updates.push(updateMs);
    }
  }
  return {
    id: "svelte",
    label: "Svelte 5",
    mountMs: round(median(mounts)),
    updateMs: round(median(updates)),
    rows: ROWS,
    runs: RUNS,
    updates: UPDATES,
    version: sveltePkg.version,
  };
}

export async function runBenchmark(): Promise<BenchmarkReport> {
  const rows = makeRows();
  const results = [
    await benchReact(rows),
    await benchVue(rows),
    await benchSvelte(rows),
  ];
  return { rows: ROWS, runs: RUNS, updates: UPDATES, results };
}