I have a “for” function performed in a jQuery draggable function. Is there a better way to do this from the execution time perspective? My function is:
$("#dragger").draggable({
containment: '#timeline',
axis: 'x',
drag: function(event, ui) {
var divs = $("#timeline div.timeline");
for (var i=0, il=divs.length; i<il; i++) {
var layer = '#layer'+i,
gow = layer+"Go";
SelectClosestKeyframes(this, event, ui, $(layer), $(gow));
}
}
});
Can I improve the for (var i=0, il=divs.length; i<il; i++)
Thanx
There’s no point in trying to optimize the loop mechanics given what you’re doing in the loop. First, I doubt you could get it significantly better anyway, and second because the cost of that loop code is dwarfed by the expense of all those jQuery calls.
You start off by finding a bunch of
<div>elements. You then iterate over that list, but your code never uses the “divs” array at all. Instead, it does 2 more jQuery lookups (albeit fairly cheap ones, as they’re based on element id) per iteration, plus whatever work is in that function.How did you come to the conclusion that the loop needs “optimization”? Is the page slow? If so, then I’d look inside that “SetClosestKeyframes” function and see what that does. Unless there are a couple million “div.timeline” elements, your problem is not the loop itself.