17th January 2010
The text below was posted on my old blog in August, 2008. Since I still use this technique, I think it is worth moving it here.
Sometimes, you need to know how many times a function was executed and how much time did it take. It is not a problem if you have good profiling tools, but sometimes they are not available. A few months ago I was optimizing my code in some very early Fx3 build and the tools I use were not ready yet (Firebug was too buggy to use and Venkman didn’t work at all). So I was on my own. Fortunately, in javascript, you can monkey patch already created functions and insert your profiling code there:
function p_register(func_name) {
var func = window[func_name];
var h_name = "__" + func_name + "__";
window[h_name] = func;
window[func_name] = function() {
// start profiling
var result = window[h_name].apply(window, arguments);
// store profiling results
return result;
};
}
In the code above, I’ve copied the function and replaced the original with a new one which contains my profiling code and a call to the hidden copy. So, every call to a function I wanted to profile was counted. As for the bottleneck, it was about prototype.js, its `Element.hasClassName` method and elements extension: it was too expensive to use them with a lot of elements, so I wrote a tiny func which acted just as `.hasClassName` but without element extension.