Mikelis Baltruks Mikelis Baltruks - 7 months ago 9
HTML Question

Pros and cons of specific looping (html elements) approaches

I have JS generated html part, that looks like this:

<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>


I am looping through them like this:

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


But I can also go:

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


So the question is: Which way would be better performance-wise and is there any significant difference?

And maybe there is another - better way?!

max block count is about 10`000, but it's theoretically infinite. It grows during the game.

Answer

I'm fairly certain that the cost of $("#block_"+i) will be high enough, compared with $(this), that it will offset any performance gains you'd get by using a more efficient for loop. This would probably be slightly more efficient:

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

However, quite certain that whatever else you're doing in your loop will be expensive enough that you won't see a significant improvement either way.

If performance is a concern here, I'd recommend you take a high-level approach to see if you can make any large-scale improvements on a design or algorithmic level. Otherwise, just use the code that's easiest to maintain.