JS looping and populating array. Which is faster?

I just saw a video of [Nicholas Zakas of Yahoo][1], at GoogleTalks talking about speeding up your website. One of the things he mentioned was doing loops in reverse order to skip one of two comparisons: `for (i = len; i--;) {}` And he said to keep away from JS libraries implementations of `for each`. Just for fun I thought I'd try it out. Turns out he was wrong. var array1 = new Array(); var array2 = new Array(); var start = 0; var finished = 0; start = (new Date).getTime(); $("#newDivTest").children().each(function(i){ array1[i] = $(this).get(0).id; }); finished = (new Date).getTime() - start; alert(finished); start = (new Date).getTime(); var len = $("#newDivTest").children().length; for (i = len; i--;) { array2[i] = $(this).get(0).id; } finished = (new Date).getTime() - start; alert(finished); newDivTest holds 1000 empty divs with an id starting at "0" and going up to "999". Another note is that `$(this).get(0).id` is about 3 times faster than `$(this).attr("id")` for some reason, anyone know why? For FF3.5, the results are "7" and "45", IE7 gives "30" and "45", Chrome2 gives "4" and "17", Opera10 gives "16" and "16", and lastly Safari4 gives "4" and "16". So it seems the approach Nicholas is hardest against is actually the faster in almost all instances. I'm not smart enough to know what's going on behind the scenes for jQuery's `each()`-method, but it must be doing something right...right? [1]: http://www.youtube.com/watch?v=mHtdZgou0qU
this should not work, because in "array2[i] = $(this).get(0).id;" this is a global scope, not a div.

以上就是JS looping and populating array. Which is faster?的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准