JavaScript Profiling With The Chrome Developer Tools

Advertisement

Your website works. Now let’s make it work faster. Website performance is about two things: how fast the page loads, and how fast the code on it runs. Plenty of services make your website load faster, from minimizers to CDNs, but making it run faster is up to you.

Little changes in your code can have gigantic performance impacts. A few lines here or there could mean the difference between a blazingly fast website and the dreaded “Unresponsive Script” dialog. This article shows you a few ways to find those lines of code with Chrome Developer Tools.

Establish A Baseline

We’ll look at a simple application called a color sorter, which presents a grid of rainbow colors that you can drag and drop to mix up. Each dot is a div tag with a little CSS to make it look like a circle.

The Color Sorter

Generating my rainbow colors was a little tricky, so I got help from “Making Annoying Rainbows in JavaScript.”

The page loads pretty fast, but it still takes a moment and blinks a little before it paints. Time to profile the page and make it faster.

Always start performance-improvement projects with a baseline understanding of how fast or slow your application already is. The baseline will let you know whether you’re making improvements and help you make tradeoffs. For this article, we’ll use Chrome Developer Tools.

The profiler is part of Chrome Developer Tools, which is always available in Chrome. Click the “Tools” menu under the little wrench to open it. Firebug has some profiling tools, too, but the WebKit browsers (Chrome and Safari) are best at profiling code and showing timelines. Chrome also offers an excellent tool for event tracing, called Speed Tracer.

To establish our baseline, we’ll start recording in the “Timeline” tab, load our page and then stop the recording. (To start recording once Chrome Developer Tools is open, click the “Timeline” tab, and then the small black circle icon for “Record” at the very bottom of the window.) Chrome is smart about not starting to record until the page starts to load. I run it three times and take the average, in case my computer runs slowly during the first test.

Performance baseline 1

My average baseline — i.e. the time between the first request for the page and the final painting of the page in the browser — is 1.25 seconds. That’s not bad, but it’s not great for such a small page.

I want to make my code run faster, but I’m not sure what’s making it slow. The profiler helps me find out.

Create A Profile

The timeline tells us how long our code took to run, but that doesn’t help us know what’s going on while it’s running. We could make changes and run the timeline again and again, but that’s just shooting in the dark. The “Profiles” tab gives us a better way to see what’s going on.

Profilers show us which functions take the most time. Let’s make our baseline profile by switching to the “Profiles” tab in Chrome Developer Tools, where three types of profiling are offered:

  1. JavaScript CPU profile
    Shows how much CPU time our JavaScript is taking.
  2. CSS selector profile
    Shows how much CPU time is spent processing CSS selectors.
  3. Heap snapshot
    Shows how memory is being used by our JavaScript objects.

We want to make our JavaScript run faster, so we’ll use the CPU profiling. We start the profile, refresh the page and then stop the profiler.

The first profile

The first thing that’s clear from the profile is that a lot is going on. The color sorter uses jQuery and jQuery UI, which are doing a lot of stuff like managing plugins and parsing regular expressions. I can also see that two of my functions are at the top of the list: decimalToHex and makeColorSorter. These two functions take a total of 13.2% of my CPU time, so they’re a good place to start making improvements.

We can click the arrow next to the function calls to open the complete function-call stack. Expanding them, I see that decimalToHex is called from makeColorSorter, and makeColorSorter is called from $(document).ready.

Here’s the code:

$(document).ready(function() {
    makeColorSorter(.05, .05, .05, 0, 2, 4, 128, 127, 121);
    makeSortable();
});

Knowing where they’re called from also makes clear that making the colors sortable isn’t my biggest performance problem. Performance issues resulting from the addition of a lot of sortables is common, but my code is taking more time to add DOM elements than to make them sortable.

I want to start making those functions faster, but first I want to isolate my changes. A lot happens when the page loads, and I want to get all of that out of my profile.

Isolate The Problem

Instead of loading the color sorter when the document is ready, I’ll make a second version that waits until I press a button to load the color sorter. This isolates it from the document loading and helps me profile just the code. I can change it back once I’m done tuning performance.

Let’s call the new function testColorSorter and bind it to a clickable button:

function testColorSorter() {
    makeColorSorter(.05, .05, .05, 0, 2, 4, 128, 127, 121);
    makeSortable();
}
<button id="clickMe" onclick="testColorSorter();">Click me</button>

Changing the application before we profile could alter the performance of the application unexpectedly. This change looks pretty safe, but I still want to run the profiler again to see whether I’ve accidentally changed anything else. I’ll create this new profile by starting the profiler, pressing the button in the app and then stopping the profile.

The second profile

The first thing to notice is that the decimalToHex function is now taking up 4.23% of the time to load; it’s what the code spends the most time on. Let’s create a new baseline to see how much the code improves in this scenario.

The second baseline

A few events occur before I press the button, but I only care about how long it took between the times the mouse was clicked and the browser painted the color sorter. The mouse button was clicked at 390 milliseconds, and the paint event happened at 726 milliseconds; 726 minus 390 equals my baseline of 336 milliseconds. Just as with the first baseline, I ran it three times and took the average time.

At this point, I know where to look and how long the code takes to run. Now we’re ready to start fixing the problem.

Make It Faster

The profiler only tells us which function is causing the problem, so we need to look into it and understand what it does.

function decimalToHex(d) {
    var hex = Number(d).toString(16);
    hex = "00".substr(0, 2 - hex.length) + hex; 

    console.log('converting ' + d + ' to ' + hex);
    return hex;
}

Each dot in the color sorter takes a background color value in hex format, such as #86F01B or #2456FE. These values represent the red, green and blue values of the color. For example, Blue dot has a background color of #2456FE, which means a red value of 36, a green value of 86 and a blue value of 254. Each value must be between 0 and 255.

The decimalToHex function converts these RGB colors to hex colors that we can use on the page.

The function is pretty simple, but I’ve left a console.log message in there, which is just some debugging code we can remove.

The decimalToHex function also adds padding to the beginning of the number. This is important because some base-10 numbers result in a single hex digit; 12 in base 10 is C in hex, but CSS requires two digits. We can make the conversion faster by making it a little less generic. I know that the numbers to be padded each have one digit, so we can rewrite the function like this:

function decimalToHex(d) {
    var hex = Number(d).toString(16);
    return hex.length === 1 ? '0' + hex : hex; }

Version three of the color sorter changes the string only when it needs the padding and doesn’t have to call substr. With this new function, our runtime is 137 milliseconds. By profiling the code again, I can see that the decimalToHex function now takes only 0.04% of the total time — putting it way down the list.

The third profile

We can also see that the function using the most CPU is e.extend.merge from jQuery. I’m not sure what that function does because the code is minimized. I could add the development version of jQuery, but I can see that the function is getting called from makeColorSorter, so let’s make that one faster next.

Minimize Content Changes

The rainbow colors in the color sorter are generated from a sine wave. The code looks at a center point in the color spectrum and creates a wave through that center point over a specified width. This changes the colors into a rainbow pattern. We can also change the colors in the rainbow by changing the frequency of the red, green and blue.

function makeColorSorter(frequency1, frequency2, frequency3,
                         phase1, phase2, phase3,
                         center, width, len) {

    for (var i = 0; i < len; ++i)
    {
       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);

       console.log('red: ' + decimalToHex(red));
       console.log('green: ' + decimalToHex(green));
       console.log('blue: ' + decimalToHex(blue));

       var div = $('<div class="colorBlock"></div>');
       div.css('background-color', '#' + decimalToHex(red) + decimalToHex(green) + decimalToHex(blue));
       $('#colors').append(div);
       
    }
}

We could take out more console.log functions. The calls are especially bad because each is also calling the decimalToHex function, which means that decimalToHex is effectively being called twice as often as it should.

This function changes the DOM a lot. Every time the loop runs, it adds a new div to the colors div tag. This makes me wonder whether that’s what the e.extend.merge function was doing. The profiler makes it easy to tell with a simple experiment.

Instead of adding a new div each time the loop runs, I want to add all of the div tags at once. Let’s create a variable to hold them, and then add them once at the end.

function makeColorSorter(frequency1, frequency2, frequency3,
                         phase1, phase2, phase3,
                         center, width, len) {

    var colors = "";
    for (var i = 0; i < len; ++i)
    {
       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);

       colors += '<div class="colorBlock" style="background-color: #' + 
           decimalToHex(red) + decimalToHex(green) + decimalToHex(blue) + '"></div>';
    }

    $('#colors').append(colors);
}

This small change in the code means that the DOM changes once, when it adds all of the div tags. Testing that with the timeline, we see that the runtime between the click and the paint events is now 31 milliseconds. This one DOM change has brought the time for version four down by about 87%. We can also run the profiler again and see that the e.extend.merge function now takes up such a small percentage of the time that it doesn’t show up on the list.

We could make the code one notch faster by removing the decimalToHex function entirely. CSS supports RGB colors, so we don’t need to convert them to hex. Now we can write our makeColorSorter function like this:

function makeColorSorter(frequency1, frequency2, frequency3,
                         phase1, phase2, phase3,
                         center, width, len) {

    var colors = "";
    for (var i = 0; i < len; ++i)
    {
       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);

       colors += '<div class="colorBlock" style="background-color: rgb(' + 
           red + ',' + green + ',' + blue + ')"></div>';
    }

    $('#colors').append(colors);
}

Version five runs in only 26 milliseconds and uses 18 lines of code for what used to take 28 lines.

JavaScript Profiling In Your Application

Real-world applications are much more complex than this color sorter, but profiling them follows the same basic steps:

  1. Establish a baseline so that you know where you’re starting from.
  2. Isolate the problem from any other code running in the application.
  3. Make it faster in a controlled environment, with frequent timelines and profiles.

There are a few other rules to follow when tuning performance:

  1. Start with the slowest parts first so that you get the most improvement for the time spent tuning.
  2. Control the environment. If you switch computers or make any other major changes, always run a new baseline.
  3. Repeat the analysis to prevent anomalies on your computer from skewing the results.

Everyone wants their website to run faster. You have to develop new features, but new features usually make a website run slower. So, investing time in tuning the performance does pay off.

Profiling and tuning cut the final color sorter’s runtime by over 92%. How much faster could your website be?

(al) (km)

↑ Back to top

Zack Grossbart is an engineer, designer, and author. He's a founding member of the Spiffy UI project, the architect of the WordPress Editorial Calendar, and a Consulting Engineer with NetIQ. Zack began loading DOS from a floppy disk when he was five years old. He first worked professionally with computers when he was 15 and started his first software company when he was 16. Zack lives in Cambridge, Massachusetts with his wife and daughter.

  1. 1

    You have said that Chrome is smart enough not to start recording until the page starts to load, but in my case it is not like that. From the moment I click record, the timeline starts recording events. Could you please describe more acurately how do you time so perfectly the beginning of the recording?

    Thanks

    6
  2. 2

    Nice summary, about time SM has something like that in it’s archive. However, it would be nice to see part II of this for CSS, as it’s demand on CPU grow with animations, effects and increasingly complex stylesheets.

    12
  3. 3

    Nice works.JavaScript makes Chrome more exciting.

    -13
  4. 4

    Vladimir Luchaninov

    August 5, 2012 6:52 am

    Hi! Your article in Russian
    http://habrahabr.ru/post/149053/

    0
  5. 5

    Maybe you can use documentFragment (designed exactly for multiple element inserts) in your sample, something like:

    function makeColorSorter // …
    // …
    var frag = document.createDocumentFragment();
    // …
    var div = $(”);
    div.css(‘background-color’, ‘#’ + decimalToHex(red) + decimalToHex(green) + decimalToHex(blue));
    frag.appendChild(div.get(0));
    // …
    $(‘#colors’).append(frag); // instead of $(‘#colors’).append(colors);

    It can be some quickier.

    1
  6. 6

    For me the issue of the timeline not recording until you load the page is dependent on the current tab. If I open a brand new tab, start the dev tools and hit record, it works like the article states – it won’t start recording until I go back to the browser and start my page loading.

    On the other hand, if I have the timeline open on an existing tab that already has a page loaded in it (and I’m about to navigate to my page-to-be-tested) and I start recording for the timeline, it will start immediately based on the content already in the tab. When I navigate to the page-to-be-tested, it’s already well into recording information.

    So for me, every time I want to start timing as the page loads I’ve had to start with a new tab.

    0
  7. 7

    There are some cases where Chrome can get confused and start a little early. You can control this by adding the console.profile() and console.profileEnd() calls to your code. You can see more about them in the Firebug Doc under Timing and profiling.

    http://getfirebug.com/logging

    10
  8. 8

    Kieran Masterton

    June 13, 2012 9:56 am

    Agree Dmitri, I’ll look to commission something along those lines.

    2
  9. 9

    Why use the firebug docs if Chrome is so much superior to it? o.O

    cu, w0lf.

    -5
  10. 10

    Lol wut?

    2

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top