JavaScript Profiling With The Chrome Developer Tools


  

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

Slim changes within your code can enjoy gigantic performance impacts. A few lines present or there could tight the difference between a blazingly fast website and the fearsome “Unresponsive Script” duologue. This article shows you a few ways to find those lines of code with Chromium Developer Tools.

Establish A Baseline

We’ll deal a simple application named a color clerk, which presents a grid of rainbow colors that you can drag and drop to mix stirring. All fragment is a div tag with a little CSS to variety it look like a circle.

The Color Sorter

Generating my rainbow flag was a little delicate, so I got a little comfort from “Making Teasing Rainbows in JavaScript.”

The page loads pretty fast, but it still takes a moment and blinks a little since 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 engineer tradeoffs. All for this article, we’ll use Chrome Creator Tools.

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

To establish our baseline, we’ll kick off recording within the “Timeline” tab, load our page and so stop the signal. (To start recording once Cr Developer Tools is open, click the “Timeline” bill, and then the small black hoop icon for “Record” at the hugely bottom of the window.) Chrome is smart about not starting to record until the page starts to load. I run it 3 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 petition for the folio and the final portray of the folio 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 belief run faster, just I’m not secure what’s making it slow. The profiler helps me find out.

Create A Profile

The timeline tells us however long our opinion took to dash, but that doesn’t help America cognise what’s active on while it’s running. We could make changes and run the timeline again and once more, only that’s just actuation within the dark. The “Profiles” tab gives us a better road to seat what’s going on.

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

JavaScript C.P.U. chart
Shows how such CPU time our JavaScript is taking.
CSS selector profile
Shows how much CPU time is spent processing CSS selectors.
Heap snapshot
Shows how memory is being used by our JavaScript objects.

We want to make our JavaScript run faster, hence we’ll use the CPU profiling. We start the chart, refresh the leaf and then stop the profiler.

The first profile

The initial 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 peck 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 pinch a total of 13.2% of my CPU time, so they’re a good place to start devising improvements.

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

Here’s the code:

$(text).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 move into making those functions faster, but early I want to isolate my changes. A lot happens once the page loads, and I want to get all of that out of my profile.

Isolate The Problem

Instead of loading the color clerk when the document is primed, I’ll fashion 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 opinion. I can amendment it posterior once I’m done tuning performance.

Let’s call the unknown function testColorSorter and tether it to a clickable button:

operate testColorSorter() {
makeColorSorter(.05, .05, .05, 0, 2, 4, 128, 127, 121);
makeSortable();
}

Click me

Changing the application before we profile could alter the performance of the application unexpectedly. This redeploy looks pretty safe, merely I still want to run the profiler again to seat if I’ve accidentally changed anything other. I’ll create this new profile by starting the profiler, pressing the lever in the app and then stopping the profile.

The second profile

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

The second baseline

A few events occur before I press the button, simply I solitary 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 measure of 336 milliseconds. Just as with the front standard, I ran it three times and took the average time.

At this point, I know where to stare you bet yearlong the code takes to run. Present we’re ready to start fixing the nuisance.

Generate It Quicker

The profiler lonesome tells us which function is feat the hold-up, so we need to analyse it and understand what it does.

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

console.wood(‘converting ‘ + d + ‘ to ‘ + hex);
return hex;
}

All dot in the color clerk 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 standard, Blue dot has a background color of #2456FE, which means a red value of 36, a verdant value of 86 and a sapphire value of 254. All 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 in that, which is just several debugging code we can remove.

The decimalToHex function also adds padding to the beginning of the digit. 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 have the ability to make the conversion faster by making it a little less generic. I know that the numbers to be padded each mortal cardinal figure, so we can rescript 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 once it needs the padding and doesn’t have to call substr. Enclosed new function, our runtime is 137 milliseconds. Via profiling the code again, I can seat that the decimalToHex function now takes only 0.04% of the whole time — putting it way down the list.

The third profile

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

Lessen Contented Changes

The rainbow colors in the color sorter are generated from a sine wave. The belief looks At a middle point within the color spectrum and creates a wave through that midway point over a specified girth. This changes the flag into a rainbow pattern. We can also change the colors in the rainbow by dynamical the frequence of the red, green and blue.

function makeColorSorter(frequency1, frequency2, frequency3,
phase1, phase2, phase3,
central, 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 + midway);
var blue = Math.flooring(Math.sin(frequency3 * i + phase3) * width + center);

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

var div = $('');
div.css('background-color', '#' + decimalToHex(red) + decimalToHex(green) + decimalToHex(blue));
$('#colors').append(div);

}
}

We could embezzle out more table.log functions. The calls are particularly bad because all is also line the decimalToHex function, which means that decimalToHex is effectively being called extra often as it should.

This function changes the DOM a tidy sum. Each time the loop runs, it adds a new div to the colors div tag. This makes me wonder if that’s what the e.extend.integrate function was doing. The profiler makes it painless to tell with a simple experiment.

Or else of count a clean div each juncture the loop runs, I want to add all of the div tags at once. Let’s turn out a variable to hold them, and next 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(Maths.sin(frequency1 * i + phase1) * size + center);
var green = Math.floor(Math.offence(frequency2 * i + phase2) * width + center);
var blue = Math.floor(Math.failing(frequency3 * i + phase3) * width + center);

colors += '';
}

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

This petite change in the standard 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 have the ability to also run the profiler again and see that the e.extend.merge function now takes uphill such a small percentage of the example that it doesn’t show up on the list.

We could fashion the code one notch faster with removing the decimalToHex activate totally. CSS supports RGB colors, so we don’t need to someone them to hex. Nowadays we have the ability to write our makeColorSorter drive like this:

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

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

colors += '';
}

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

Version five runs within 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 multiplex than this color sorter, but profiling them follows the same basic steps:

Establish a baseline hence that you know wherever you’re starting from.
Insulate the catch from any other code running in the application.
Make it faster in a controlled environment, with frequent timelines and profiles.

There are a few various rules to chase when tuning performance:

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

Everyone wants their website to run faster. You’ve to develop foreign features, simply new features usually make a website run slower. So, investing juncture in tuning the performance does pay stale.

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

(al) (km)


© Zack Grossbart for Smashing Magazine, 2012.



Source: http://www.smashingmagazine.com/2012/06/12/javascript-profiling-with-the-chrome-developer-tools/

Advertisements
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: