示例工程 25-vue-reactivity-streaming

25-vue-reactivity-streaming/demo-01-shallow-bench/bench.ts

typescript · 1.5 KB

import { isReactive, reactive, shallowRef } from "vue";

type Event = {
  id: number;
  source: string;
  text: string;
};

function batch(start: number, size: number): Event[] {
  return Array.from({ length: size }, (_, index) => ({
    id: start + index,
    source: ["build", "network", "tools"][(start + index) % 3] ?? "build",
    text: `event ${start + index}`,
  }));
}

const rounds = 120;
const size = 60;

const deep = reactive<Event[]>([]);
const deepStart = performance.now();
for (let round = 0; round < rounds; round += 1) {
  deep.push(...batch(round * size, size));
}
const deepSum = deep.reduce((sum, event) => sum + event.id, 0);
const deepMs = performance.now() - deepStart;

let raw: Event[] = [];
const shallow = shallowRef<Event[]>(raw);
const shallowStart = performance.now();
for (let round = 0; round < rounds; round += 1) {
  raw = raw.concat(batch(round * size, size));
  shallow.value = raw;
}
const shallowSum = shallow.value.reduce((sum, event) => sum + event.id, 0);
const shallowMs = performance.now() - shallowStart;

const deepProxy = deep.length > 0 && isReactive(deep[0]);
const shallowProxy = shallow.value.length > 0 && isReactive(shallow.value[0]);

console.log(
  JSON.stringify({
    evt: "smoke",
    ok:
      deepSum === shallowSum &&
      deepMs > 0 &&
      shallowMs > 0 &&
      deepProxy &&
      !shallowProxy &&
      shallowMs < deepMs,
    rounds,
    size,
    deepMs: Math.round(deepMs * 100) / 100,
    shallowMs: Math.round(shallowMs * 100) / 100,
    deepSum,
    shallowSum,
    deepProxy,
    shallowProxy,
  }),
);