Take the following two ways of removing an array of elements from the DOM using jQuery:
var collection = [...]; // An array of jQuery DOM objects // Using jQuery iteration $(collection).each(function(index, element) { element.remove(); }); // Or as pointed out by Barmar $(collection).remove(); // Using native iteration collection.forEach(function(element) { element.remove(); });
Is there any real difference operationally? I'd expect, unless the browser interpreter/compiler is clever enough, that there would be additional unnecessary overhead with the former method, albeit probably minor if the array is small.
forEach() Method. The . forEach() method of JavaScript executes a given function once for each element of the array.
forEach is almost the same as for or for..of , only slower. There's not much performance difference between the two loops, and you can use whatever better fit's the algorithm. Unlike in AssemblyScript, micro-optimizations of the for loop don't make sense for arrays in JavaScript.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
each() function, jQuery's foreach equivalent. jQuery's foreach equivalent can be very useful for many situations. These examples will get you started and teach you how you can loop through arrays, objects and all kinds of HTML elements.
Operationally is a bit vague but here is how $.each
is implemented.
each
implementation
[].forEach()
would most likely be implemented in native code for each browser.
Without doing performance testing, they are pretty similar. Although if you can remove jQuery altogether that is at least a few kb the browser does not need to load.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With