特定循环(html元素)方法的优缺点

时间:2016-05-05 15:27:42

标签: javascript jquery html

我有JS生成的html部分,看起来像这样:

<div id="container">
    <div id="block_1" class="blocks"></div>
    <div id="block_2" class="blocks"></div>
    <div id="block_3" class="blocks"></div>
    ...
    <div id="block_n" class="blocks"></div>
</div>

我正在这样循环:

var blocks = $(".blocks");
$.each(blocks, function() {
      var val = $(this).text();
      ...
});

但我也可以去:

for (var i=1; i<=block_count; i++) {
    var val = $("#block_"+i).text();
    ...
}

所以问题是:哪种方式在性能方面会更好,是否存在显着差异?
也许还有另一种 - 更好的方法?!
最大块数约为10,000,但理论上它是无限的。它在游戏中增长。

3 个答案:

答案 0 :(得分:3)

Javascript中有大量的性能提示。

请看一下:What's the fastest way to loop through an array in JavaScript?

你会发现非常有用的信息,但TL; DR这是目前最适合你的情况的循环:

var blocks = document.getElementsByClassName("blocks");
for (var i=0, len = blocks.length; i<len; i++) {
    var val = blocks[i].textContent;
    ...
}

答案 1 :(得分:1)

我相当确定$("#block_"+i)的成本与$(this)相比足够高,它会通过使用更高效的{{1}来抵消您获得的性能提升。 }循环。这可能略微更有效:

for

然而,非常肯定的是,无论你在循环中做什么,都会花费很多,以至于你不会看到任何重大改进。

如果在这里考虑性能,我建议您采用高级方法,看看是否可以在设计或算法级别上进行任何大规模的改进。否则,只需使用最容易维护的代码。

答案 2 :(得分:0)

通常,您的代码应避免在不需要时使用选择器和jQuery构造函数。代码的更高性能版本只构造一次元素,如下所示:

// Save the reference to the entire collection; you'll need to update
// this as the list grows. You can use blocks.add() to add the newly
// created elements to the same set. It is _potentially_ faster than
// having to reselect the entire collection each time.
var blocks = $('.blocks', '#container');

// Iterate over each item using the callback function which
// receives the index number (0-indexed) and the actual
// HTMLElement in each iteraction
blocks.each(function(idx, item) {

  // `this` and `item` are the same thing in this case
  console.log(this === item);

  // `item` is an HTMLElement, it's not a wrapped jQuery object
  var text = item.textContent;

  // you can also get the jQuery item object by using the index;
  // this doesn't require you to construct a new jQuery object
  var $item = blocks.eq(idx);

  var value = $item.val();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这个和你的例子之间的区别在于你不必继续重新选择和重建对象,这更快。在这种情况下使用for()$.each()之间没有明显区别。