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

Pros and cons of specific looping (html elements) approaches

本文关键字:缺点 方法 循环 html 元素      更新时间:2023-09-26

我有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();
    ...
}

所以问题是:哪种方式的性能更好,有什么显著差异吗
也许还有其他更好的方法
最大块数约为10000,但理论上是无限的。它在比赛中生长。

在Javascript中有很多性能提示。

请看这里:What';用JavaScript循环数组的最快方法是什么?

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

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

我很确定,与$(this)相比,$("#block_"+i)的成本将足够高,它将抵消使用更高效的for循环所带来的任何性能提升。这可能会稍微高效一些:

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

然而,可以肯定的是,无论你在循环中做什么,都会非常昂贵,无论哪种方式,你都不会看到显著的改进。

如果性能是一个问题,我建议你采取一种高级方法,看看你是否可以在设计或算法层面上进行任何大规模的改进。否则,只需使用最容易维护的代码。

通常,您的代码应该避免在不需要时使用选择器和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()没有明显区别。