Profiling JavaScript

Page 1 - Profiling in Firefox

A yellow speed camera

Skip to navigation

Jul
29

JavaScript can be a memory hog at times, and it's not something you really want to stick with when a new project goes live. Instead you should profile your code in order to find out what needs to be optimised.

Firefox has a great advantage when it comes to profiling, and ultimately profiling code due to it's ability to have extensions easily installed. For this article it is required that you have FireBug installed as this will be the tool used in profiling. It is possible to profile the code using other tools and extensions such as the Venkman debugger but I will not cover them here.

Once you have Firebug installed navigate to your page and then open up the Firebug console tab. On this tab you will see a button along the top labelled "Profile". From the second you click this, any JavaScript that is run will be profiled. So if you enable this now and then do a forced refresh of your page by pressing either Ctrl-F5 on the PC or Apple and F5 on the Mac you will reload the page ignoring the cache. This is to make sure that any files that are required are downloading afresh just as it would for any new visitor to your site.

Enabling Profiling

Once you have done loading the page, press the Profile button again and the profiling will end showing a summary that appears like the following.

Profile Summary

From this summary we can see which functions are taking the longest to complete, how many times they are running, what percentage of the Javascript loading time it uses, and the average completion time. By clicking on the function we can find whereabouts in the code it is called from. This can help track down where any slow loading is coming from and shows where you need to optimise.

With Firefox there is also an alternative, though in my opinion it is not as good as Firebug, and that is the Venkman JavaScript Debugger. Also worth mentioning is that Yahoo! recently released the YSlow plugin for Firebug that is supposed to help you profile your code - though so far it seems absolutely pointless as the majority of information it provides is already available in FireBug.