doug crockford has a posse.

Cross-browser Javascript Profiling with YUI

Soon the fabulous YUI team will release a skin for their profiler tool. This release will hopefully bring profiling mainstream, if Firebug hasn't done it already (and what sadly Venkman failed to do.) More importantly, it will bring this indispensable benchmarking technique to all A-grade browsers and platforms, and in a manner that will be accessible to the average web developer.

Hot stuff!

But why wait? This is not difficult to accomplish with the tools already they've provided us.

To start, you'll need to include a few dependencies from Yahoo.

<link type="text/css" rel="stylesheet" href="http://yui.yahooapis.com/2.4.1/build/logger/assets/skins/sam/logger.css">
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/utilities/utilities.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/logger/logger-min.js"></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/profiler/profiler-beta-min.js"></script>

Next, we'll obviously need something to profile, so let's write a simple function that creates a div from scratch. We'll then register the function with the Profiler tool.

function createDiv (){
   return document.createElement('div');
}

YAHOO.tool.Profiler.registerFunction('createDiv', window);

That's it. We're already to run our test, so let's call createDiv() a bajillion times to create some data.

for(var i=0; i<5000; ++i){
   createDiv();
}

Profiler offers you a bunch of different methods to slice and dice your results. Most likely you're gonna want to find the average duration (getAverage), but you can also retrieve the maximum, minimum, and even how many times the function was called.

Now let's finish up and get some result.

//Create a new instance of the Logger widget (we'll use this panel to display our results.)
var logger = new YAHOO.widget.LogReader('logger');

var avg = YAHOO.tool.Profiler.getAverage('createDiv');

//Write the results
YAHOO.log('The average duration of creatDiv() was: ' + avg);

Try it out!


No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment

Yuidocs.com : Faster access to YUI Documentation Don’t make me think