Cover by Cody Lindley

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

5.8. Finding the Bottlenecks

Problem

Your site is too slow to load or too slow to respond to clicks and other user interaction, and you don’t know why. What part of the code is taking so much time?

Solution

Use a profiler, either one of the many available ones or a simple one you can code yourself.

Discussion

A profiler is a way to find the parts of your code that take the most time. You probably already have at least one good JavaScript profiler at your fingertips. Firebug has one, and others are built into IE 8 and Safari 4. These are all function profilers: you start profiling, interact with your page, and stop profiling, and then you get a report showing how much time was spent in each function. That may be enough right there to tell you which code you need to speed up.

There are also some profilers specific to jQuery that you can find with a web search for jquery profiler. These let you profile selector performance and look more deeply at jQuery function performance.

For really detailed profiling, where you need to analyze individual sections of code smaller than the function level, you can write a simple profiler in just a few lines of code. You may have coded this ad hoc classic:

var t1 = +new Date;
// ... do stuff ...
var t2 = +new Date;
alert( ( t2 - t1 ) + ' milliseconds' );

Note

The +new Date in this code is just a simpler way of coding the more familiar new Date().getTime(): it returns the current time in milliseconds.

Why does it work? Well, the new Date part is the same: it gives ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required