Yahoo User Interface (YUI) provides a very good feature to profile your javascript code. One can measure the performance of their code in the terms of the number of times the function call, average time, minimum time,
maximum time taken by a code block or script to execute. The best feature I feel with YUI code profiler is the ability to profile a specific code block like functions. Here I am going to present how to create a profile using YUI profiler for a code block:
Include the code profiler source file in your script:
<script type=”text/javascript” src=”http://yui.yahooapis.com/2.7.0/build/yahoo/yahoo.js”></script>
<script type=”text/javascript” src=”http://yui.yahooapis.com/2.7.0/build/profiler/profiler-min.js”></script>
HTML block:
<div id=”p_report”></div>
<input type=”button” name=”d_profile” id=”d_profile” value=”Create Profile”>
JavaScript:
YAHOO.util.Event.on(‘d_profile’, ‘click’, function(){
YAHOO.tool.Profiler.registerFunction(“pObject.sayHello”);
var pObject = {
sayHello : function(){
return “Hello”;
}
};
//register method on a global object – no second argument needed
YAHOO.tool.Profiler.registerFunction(“pObject.sayHello”);
//alternate – providing second argument
YAHOO.tool.Profiler.registerFunction(“pObject.sayHello”, pObject);
//call this function
var hello = pObject.sayHello();
var calls = YAHOO.tool.Profiler.getCallCount(“pObject.sayHello”);
var max = YAHOO.tool.Profiler.getMax(“pObject.sayHello”);
var min = YAHOO.tool.Profiler.getMin(“pObject.sayHello”);
var avg = YAHOO.tool.Profiler.getAverage(“pObject.sayHello”);
YAHOO.tool.Profiler.unregisterFunction(“pObject.sayHello”);
document.getElementById(‘p_report’).innerHTML =
“pObject.sayHello(): was called ” + calls +” times.<br>”+
“The average time was ” + avg + “ms.”+”<br>”+
“The max time was ” + max + ” ms.” +”,<br>”+
“The min time was ” + min + ” ms.”;
});
The HTML part will display a button “Create Profile”. Clicking on that button will generate the report of the pObject.sayHello() function call and display the result in the div with id “p_report”.
This is just an example of how to use YUI code profiler. Hope this will help creating code profiles.