Jest 中的 JS 基准测试 - 日期到数字

问题描述 投票:0回答:1

我试图在本地对

Number(new Date())
+new Date()
进行基准测试。我已经回答了我自己的问题,让其他人受益,但我欢迎任何改进。

typescript date jestjs numbers
1个回答
0
投票

benchmarking.test.ts

function benchmarkFunction(func: Function) {
  const start = window.performance.now();
  const result = func();
  const end = window.performance.now();
  return {
    time: end - start,
    result: result
  };
}

describe("Benchmark Date methods and operations", function () {
  const dates = [];
  for (let i = 0; i < 10000000; i++) {
    dates.push(new Date(i));
  }

  const dateToNumberByMethod = benchmarkFunction(() => {
    const convertValues = [];
    for (let i = 0; i < dates.length; i++) {
      convertValues.push(Number(i));
    }
    return `${convertValues.length.toLocaleString('en-GB')} operations`;
  });

  const dateToNumberByOperator = benchmarkFunction(() => {
    const convertValues = [];
    for (let i = 0; i < dates.length; i++) {
      convertValues.push(+i); // convert Date by + operator
    }
    return `${convertValues.length.toLocaleString('en-GB')} operations`;
  });

  test("Date to Number conversion - Operator should be quicker", () => {
    console.debug({
      dateToNumberByMethodInMs: dateToNumberByMethod,
      dateToNumberByOperatorInMs: dateToNumberByOperator
    });

    expect(dateToNumberByMethod.time).toBeGreaterThan(dateToNumberByOperator.time);
  });
});

export {};

结果:

{
  dateToNumberByMethodInMs: { time: 1144.5782999999997, result: '10,000,000 operations' },
  dateToNumberByOperatorInMs: { time: 369.08829999999944, result: '10,000,000 operations' }
}

奇怪的是,差异可能有很大差异,但操作员总是更快。我不相信使用 Jest 适合进行基准测试,但我感兴趣的是更快的速度,而不会因库等而变得臃肿。

© www.soinside.com 2019 - 2024. All rights reserved.