开发者

jQuery/Javascript "for" function performance improvement

I have a "for" function performed in a jQuery draggable function. Is there a better way to do this f开发者_StackOverflow社区rom 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.


http://www.websiteoptimization.com/speed/10/ is a good resource that I've used before for optimizing javascript loops.


I would look to refactor the SelectClosestKeyframes function so it is bound to the div's with timeline class. And/or use "each".


Not that this would be any faster, just cleaner:

var dragable = this;
$("#timeline div.timeline").each(function(i) {
   SelectClosestKeyframes(dragable, event, ui, $('#layer'+i), $('#layer'+i+'Go'));
});

In fact the each() will be a little slower than your for() but on a very minute scale.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜