Finding the Bottlenecks - J Query

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?


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


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:

We can make something more general-purpose and easier to use with only 15 lines of code:

Now we have a time() function that we can call as often as we want to log the elapsed time since the last time() call (or, optionally, since a specific prior time). When we’re ready to report the results, we call time.done(). Here’s an example:

That JavaScript code requires this HTML code to be added to your page:

We can see that the largest amount of time is being spent between the time('first')
andtime('second') calls.
For many optimization exercises, this code may be sufficient. But what if the code we need to test is inside a loop?

Now our little profiler will list those first, second, and third entries 10 times each! That’s not too hard to fix—we just need to accumulate the time spent for each specific message label when it’s called multiple times:

With this change, we’ll get useful results from that loop:
0.973 first
9.719 second
0.804 third
11.496 total

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics