Profiling JavaScript with Firebug. console.profile() & console.time()!

Firebug and the console object

Although my impression is that most of the web developers use Firefox and most of them are using Firebug, I’m not sure that they use the full potential of this brilliant software.

Firebug’s console view

Firebug is a very powerful tool helping those like me doing his job. But what’s behind the mostly used Firebug’s tools and what’s in the API.

console.log()

For a typical JavaScript programmer the console.log() function is one of his best friends. It can dump useful information in the console tab of the Firebug making everything quite clear. But have you ever asked yourself how to improve your code, how to measure its performance against some constructions.

Performance of JavaScript

I’m sure many of us have read enough articles out in the web about JS performance. Nowadays when the web apps become bigger and bigger, this topic is rising from the bottom of the interesting topics pool. Now everybody’s concerned about it’s app performance and speed.

You’ve probably heart about some basic advices. What to use, what not to use. In a short example I’ll mention only that everybody knows that .appendChild is far slower than the innerHTML. But why is that? How can be sure it’s true.

As I wrote recently you should instantiate your new arrays in javascript with the following construction:

var a = [];

instead of:

var a = new Array();

but as I’ll write here that’s not always true.

console.profile()

One of the useful methods of the Firebug’s console object is the profile() method. It gives you the power to measure timing and performance of any JS function. As described in the Firebug’s web page:

The high-fi approach is to use the JavaScript profiler. Just call console.profile() before the code you want to measure, and then console.profileEnd() afterwards. Firebug will log a detailed report about how much time was spent in every function call in between.

With the simple construction like:

<html>
<body>
<script>
    myFunc = function() {
        var a = [];
    }				

   console.profile();
   myFunc();
   console.profileEnd();
</script>
</body>
</html>

Firebug’s profile output

The simple problem is that thus you cannot just measure some code that’s not a function. This will result in empty profile output in the console’s view:

But hopefully there comes the other method of the console object.

console.time()

It gives anything you’d like to know even if it’s not closed into a function.

Note: remember that both profile and time methods goes with their related profileEnd and timeEnd methods. You’re supposed to enclose the chunk of code you measure with that to be sure that the Firebug’s console will stop the profilers on time.

Now you can simply ask the profiler: what is faster?

Leave a Reply

Your email address will not be published. Required fields are marked *