Sunday, February 14, 2016

JavaScript : measuring performance

I recently learned a couple great tricks for measuring performance in JavaScript. There's always the profiler in the browser, but that's a bit verbose if you need to just A/B two ways of doing something. The following techniques are great lightweight approaches that you can use when writing or performance tuning some code.


1. performance.now()


basically it returns NOW as in RIGHT NOW which you can capture in a var for later use. Here's a basic pattern for use:


var s = performance.now();
//do something
console.log(performance.now() - s);


this will log the time "do something" took to complete in ms.


performance is a property of the window object, therefore it is NOT available on nodejs. You can use the following in that environment:


2. console.time("key"); console.timeEnd("key");


use it like this:


console.time("key");
//do something
console.timeEnd("key");


depending on the js engine, you'll get an output like:


"key" 3.002 ms


If you want to measure more than just the execution time, like memory usage, i/o usage, and processor use these quick-and-dirty functions won't get you that. Look for a future post on those topics...

No comments:

Post a Comment