Sitemap

Easy Javascript Time Profiling

2 min readOct 24, 2014

Using Chrome’s Developer Console

I’m a relative newcomer to the world of front end development. I shudder to think of what life was like before the days of the magical Chrome console. I probably spend 50% of my day using it, and learn a new trick every week (now every day: http://devtoolstips.com/).

Last week I wrote a function that processed some data every time a user clicked on an element before re-rendering it on the screen. There was a noticeable delay in the rendering but it was tough to determine if this was caused by the data processing or the rendering function itself. My mentor informed me that my target for data processing function should be under ~16 milliseconds.

Time profiling this function was incredibly simple using Chrome’s developer console. Just throw in

"console.time(<some_name>)"

right before the line where you want to start the timer and

"console.timeEnd(<some_name>)"

right after the line where you want to end it.

Get Jesse Sessler’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s say you want to look at the difference in performance of two different functions, one using JQuery and one using vanilla JS. Let’s add 1,000 paragraphs to the DOM using insertBefore, because that seems like a fun and practical thing to do.

function addParagraphs() {
console.time('js adding paragraphs');
var n = 1000;
for (var i = 0; i < n; i++) {
var placeHolder = document.getElementById('placeholder');
var paragraph = document.createElement('P');
var textNode = document.createTextNode('Test Paragraph');
paragraph.appendChild(textNode);
document.body.insertBefore(paragraph, placeHolder);
}
console.timeEnd('js adding paragraphs');
}
function jqAddParagraphs() {
console.time('jq adding paragraphs');
var n = 1000;
for (var i = 0; i < n; i++) {
var placeHolder = $('#placeholder');
var paragraph = $('<p>Test Paragraph</p>');
paragraph.insertBefore(placeholder);
}
console.timeEnd('jq adding paragraphs');
}
Press enter or click to view image in full size

Looks like in this case vanilla JS is 20 times faster than JQ. And it took all of 4 lines and about 2 minutes to determine that.

There you have it, a quick and easy way to time profile functions in javascript.

Documentation and some other nifty Chrome console tricks here: https://developer.chrome.com/devtools/docs/console-api. If you thought this was handy definitely check out console.profile. Let me know what you think on twitter!

Jesse Sessler
Jesse Sessler

Written by Jesse Sessler

Front End / Mobile developer @deliverydotcom.