Which one performs better a function or an object in Javascript/Jquery?
//Object approach
$.myutils = {
addNumbers : function(a,b){
//assuming a and b are integers for simplicity
return a + b;
}
subNumbers : function (a,b){
//assuming a and b are integers for simplicity
return a - b;
}
};
//Usage
$开发者_开发知识库.myutils.addNumbers(20,10);
$.myutils.subNumbers(20,10);
//function approach
$.myutils = function()
{
return {
addNumbers : _addNumbers,
subNumbers : _subNumbers
};
_addNumbers : function(a,b){
//assuming a and b are integers for simplicity
return a + b;
}
_subNumbers : function (a,b){
//assuming a and b are integers for simplicity
return a - b;
}
}
//Usage
$.myutils().addNumbers(20,10);
$.myutils().subNumbers(20,10);
While this could be considered the case of premature optimization, consider the case that the semantics are different and the first method is likely preferred (as there is no additional state stored).
Anyway, the first "objects" method is "faster" (for some value of "faster") because the same functions which are properties of the same object are invoked.
The second "functions" method will be "slower" (for some value of "slower") because each time the myutils
function is executed (but remember, functions are also objects) it return a new object that has new functions as properties. Thus, just by definition is has to do more work. (Also, the second method will not run as it is, I translated it to "working code" in my head.)
Happy coding.
Following zerkms's comment, I have added a jsperf test-case: http://jsperf.com/5931661 (It also includes appropriate bug-fixes; both "examples" were actually broken).
Short answer: an object is faster.
Your function returns an object - why would it be faster than a direct object??
精彩评论