A friend of mine (who is much more skilled with javascript than I am) was helping me optimise some code recently, and one of the things that he mentioned might help was to call an external function instead of using a scoped function. However, it appears that this actually doesn’t appear to have much if any impact on performance. Would anyone who is more familiar with the inner workings of javascript mind explaining why this is the case? Is there any any reason to use one method over another?
What I mean is, this:
function showI(e) {
var iVal = $(e).attr('iteration');
var iValx99 = iVal * 99;
var iValx999 = iVal * 999;
alert(iVal + ' // ' + iValx99 + ' // ' + iValx999);
}
var element;
for (var i = 0; i < 50; i++) {
element = $('<div />', {
'class': 'iteration',
'iteration': i
});
element.on('click', function() {
showI(element);
});
element.appendTo('body');
}
versus:
var element;
for (var i = 0; i < 50; i++) {
(function() {
var j = i;
element = $('<div />', {
'class': 'iteration'
});
element.on('click', function() {
var iVal = j;
var iValx99 = iVal * 99;
var iValx999 = iVal * 999;
alert(iVal + ' // ' + iValx99 + ' // ' + iValx999);
});
element.appendTo('body');
})();
}
jsperf benchmark example:
http://jsperf.com/function-click-on-every-element-vs-calling-a-function/2
Well, you are throwing away the performance gains from using a static function by defining a new function everytime anyway.
What he probably meant was to use this:
You don’t even need to bind it 50 times:
And modify
showI:This is much faster in the modifed jsperf http://jsperf.com/function-click-on-every-element-vs-calling-a-function/3
jsfiddle: http://jsfiddle.net/RgU5z/