The academically correct way to benchmark JavaScript code?

462 Views Asked by At

I'm currently writing a paper. In this paper, I'm going to talk about optimization of code. In my example, I'm going to distinct two arrays in JavaScript. Comparing ES5 filter vs nested for loop.

My tests using jsPerf.com went as expected. ES5 filter is 89-90% slower than a nested for loop. Similar result could be found using performance.now() (starting a timer, running code, stopping timer, and calculating the time taken).

All of these are great for benchmarking code. Really, they are. However, they're not academically correct. Right after the first test is done, what happens if I run a 100% CPU intensive benchmark? Test 2's results are "invalid" then.

What is the best way, the correct way, to benchmark two pieces of JavaScript code?

1

There are 1 best solutions below

0
MortenMoulder On

I found the answer. Using Google Chrome's Profiler I was able to get the CPU time of my function.

Using a profiler seems like the best way to do this, as it actually uses the CPU time instead of actual time. The result should not be affected, even if my CPU runs at 100% in one of the tests.