January 7, 2015 by Christoff Truter JavaScript
Over the last decade or so, JavaScript evolved quite a bit, mostly (if not primarily) thanks to the advent of Web 2.0 and technologies like HTML5 introducing powerful API's.
It is quite breath-taking what developers are currently achieving with JavaScript, if you haven't visited the chrome experiments website yet, do yourself a favour and do so now - you won't be disappointed. JavaScript is no longer merely a cheap thrill, but it has become an essential part of modern web development, to be blunt, its got balls now ;)
Which means it is becoming more and more crucial to check the performance of the JavaScript we write.
There are a number of ways to benchmark JavaScript, one can make use of a JavaScript benchmarking library like benchmark.js or an online service like jsperf.com for test cases (while getting input from others).
In this post however, we are going to have a quick look at how to use the Console API (supported by most modern browsers) to benchmark our code.
You might recognise the scenario in the following snippet - the whole prototype vs this in constructor performance question.
function TestCase1() { this.SomeFunction = function() { return true; } } function TestCase2() { } TestCase2.prototype.SomeFunction = function() { return true; }
In the next snippet I make use of the console time and timeEnd timer functions in order to determine which test case performs the best.
console.time('TestCase1'); for (var i = 0; i < 1000000; i++) { new TestCase1(); } console.timeEnd('TestCase1'); console.time('TestCase2'); for (var j = 0; j < 1000000; j++) { new TestCase2(); } console.timeEnd('TestCase2');
Within your browser console window, you will see something like this:
The Console API is an extremely useful tool, you can also profile your code, record timelines, use assertions etc.
You can read more about it over here.
April 9, 2015
Javascript Tip: Event PropagationJuly 25, 2010