Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.each vs. JavaScript .forEach

Tags:

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.

like image 710
Lee Avatar asked Feb 12 '17 17:02

Lee


People also ask

Is forEach JavaScript or jQuery?

forEach() Method. The . forEach() method of JavaScript executes a given function once for each element of the array.

Is forEach faster than for JavaScript?

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.

Which is faster for or forEach?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Can we use forEach in jQuery?

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.


1 Answers

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.

like image 127
dpix Avatar answered Sep 20 '22 01:09

dpix