I was trying to benchmark Number(new Date())
vs +new Date()
locally. I’ve answered my own question for others to benefit but I welcome any improvement.
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 {};
results:
{
dateToNumberByMethodInMs: { time: 1144.5782999999997, result: '10,000,000 operations' },
dateToNumberByOperatorInMs: { time: 369.08829999999944, result: '10,000,000 operations' }
}
Strangely, the difference can vary significantly but the operator is always faster. I’m not convinced using Jest is appropriate for benchmarking but all I’m interested in is what’s faster, without bloating with libraries etc.