JavaScript: Timing/Benchmark JS Code
Simple timing of a function
To get the timing of a JavaScript function, you just get a time stamp. Like this:
// the function to test function range(n) { const arr = Array(n); for (let idx = 0; idx <= n; idx++) { arr[idx] = idx; } return arr; } { // timing const test_repeat_count = 50; const start = new Date().getTime(); for (let i = 0; i < test_repeat_count; ++i) { range(9999); } const end = new Date().getTime(); // result console.log(end - start); }
Benchmark JavaScript Code Using Deno Bench
a better way is to use deno's builtin bench API.
https://deno.land/manual/tools/benchmarker
First, you need to create a file. Let's say
bench.js
// bench.js // 2022-07-10, 2022-08-27 // comparing speed of n = n + 1 vs n++ const f1 = ((x) => { let n = 1; for (let i = 1; i < x; i++) n = n + 1; return n; }); const f2 = ((x) => { let n = 1; for (let i = 1; i < x; i++) n++; return n; }); console.log(f1(10) === 10); console.log(f2(10) === 10); Deno.bench("normal assign", () => { f1(10_000); }); Deno.bench("plus plus", () => { f2(10_000); });
In the script, call
Deno.bench( a_name_string, arrow_function_of_no_arg);
then, in terminal, run this:
deno --unstable bench bench.js

this means,
n = n + 1
and
n++
have the same speed.