The Issue
Cannot believe I could not find anything on this around the net, maybe I am searching for the wrong thing…
There is probably little or no difference at all, but as I am trying to optimize my code as best I possibly can, I feel it is worth asking.
Very simply, I would like to know whether defining and running a method in an object processes faster than defining and running a function globally.
Examples
Consider this:
(function($){
$.fn.test = function() {
// do something here
};
})(jQuery);
And this:
function test(){
// do something here
}
My Question
Which of the above is faster and why? If there is no difference in speed then which would you advise using?
Thanks in advance
UPDATE 1
As it may be relevant, I feel it is necessary to explain why I am asking this question. I have a library that I have written over the years that contains a large variety of functions. As there are so many of them, I want to know whether they would run faster if I was to extend the jQuery object, or keep them as they are?
In theory, you just need to count the number of objets that must be searched to determine which will be faster. Variables are resolved against the scope chain, the script engine must first search the function’s execution context, then the outer contexts, and finally the global context.
Property resolution must first find the object on the scope chain, then the property on the object or its
[[Prototype]]chain.But in practice, compiler optimisation means the above simplistic analysis is will be wrong as often as it is right, and also deliver different results in different browsers for different cases.
Generally, such optimisations deliver minuscule changes in performance and should not be considered purely for performance reasons. Design objects and methods for whatever makes sense for your application architecture, ease of maintenance and logical grouping.