This question relates to a previous question here:
Reducing number of calls to the methods of a JavaScript object
When profiling these two code snippets with Firebug:
function ie6PNGFixLoader(scriptURL) {
if(arguments.length > 0) {
for (var i = 0; i < arguments.length; i++) {
$.ajax({// load PNG fix scripts
url: arguments[i],
cache: true,
dataType: 'script'
});
}
} else {
return false;
}
}
var pngFix = "/Global/ICIS/Scripts/DD_belatedPNG_0.0.8a-min.js";
var pngList = "/Global/ICIS/Scripts/DD_PNG_listing.js";
ie6PNGFixLoader(pngFix, pngList);
and
function InjectScriptsAndExecute(url) {
this.url = url;
}
InjectScriptsAndExecute.prototype.InjectMethod = function() {
var inject = $.ajax({
url: this.url,
cache: true,
dataType: 'script',
async: false, // Otherwise you cannot depend on the parse order
});
return inject;
}
var pngFix = new InjectScriptsAndExecute("/Global/ICIS/Scripts/DD_belatedPNG_0.0.8a-min.js");
var pngList = new InjectScriptsAndExecute("/Global/ICIS/Scripts/DD_PNG_listing.js");
pngFix.InjectMethod();
pngList.InjectMethod();
It appers that the latter’s calls to the InjectScriptsAndExecute method are much faster than the former’s calls to its function. A colleague has asked me why when i mentioned the performance improvement but i cannot explain it myself.
Any advice for better understanding would be greatfully received.
Arguments is not
Arrayit’s anObjectthat somewhat behaves like an array.Cache the length, accessing the property is slow, IE6 won’t have no optimization at all for
.lengthand I even suspect it to be really slow when using thearguments[i]since it is not a realArrayand might therefore do an unoptimized property lookup.If you want to get the best of both worlds, pass a normal
Array, use a plainforloop, andcachethelength.EDIT
To make it clear, timing the loop is useless, the request is async, all you do is timing a loop and a call to
$.ajaxthere’s no point in optimizing here, especially not for two entries. Even in IE6, doing the Ajax call itself (even just calling$.ajax) will be way slower then the loop.