I decided to blog today about one of my favorite (and least talked about) Firebug feature: Javascript Profiling. This could be become very relevant with web apps increasing in client side complexity and functionality. Also browsers are starting to support various advanced concepts and controls that will invite even more javascript development.
I personally don't do javascript profiling often. More likely I will use it to make sure that the rough numbers I see after profiling don't look anything out of ordinary. For instance, one of the web apps I was prototyping, I was using jquery to select various html dom elements in a very inefficient way. Since it was a prototype, I really didn't care as long as I got the functionality in and could see how things worked. Once time came for cleanup, I used profiling to see what places I am making incredible amount of calls needlessly.
So to get started, with Firebug up and visible (F12), click on "Profile" tab.
Click on "Profile" again to stop it. If you were running this on an empty page, you will see "No activity to profile." text. But if there was some javascript running (something running periodically for instance), you would see some timing data coming in. This is a great way to see what the site is running on a periodic bases by the way.
To illustrate time measurement I will use a silly example. Let me create a simple page that when clicked on a button will find all the spans with-in divs with attribute "doHide" set to true and hide them. To do this, I will use jquery for selecting:
function hideThem() {
$("div > span[@doHide=true]").hide();
}
I will start profiler running, click on the Hide them button and click on "Profile" again to get the results. Here is how they look:
So, 216 calls to hide some spans. That won't do. How about we just assing a special class to the spans and use that in selecting the spans to hide:
Results:
Kind of better since total time now is really negligible (unless the number of spans being hidden increases a lot). 168 calls, less, but still a lot.
Again, you do this only if you notice something is working slower than it should. Don't get bothered much with optimizing simple javascript, make it readable and cross-browser usable your first priority. But from time to time check your work if you feel that javascript is awefully slow and you are looking to speed it up. By using the profiler you will know where to speed it up.