Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more Efficient array.forEach or angular.forEach?

array.prototype.forEach

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

Source: https://developer.mozilla.org/enUS/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

angular.forEach

Invokes the iterator function once for each item in obj collection, which can be either an object or an array. The iterator function is invoked with iterator(value, key, obj), where value is the value of an object property or an array element, key is the object property key or array element index and obj is the obj itself. Specifying a context for the function is optional.

Source: https://docs.angularjs.org/api/ng/function/angular.forEach

But I want to know which one is more efficient and the performance.

like image 207
rittam Avatar asked Jun 17 '16 07:06

rittam


People also ask

Which is efficient for or forEach?

The foreach loop is considered to be much better in performance to that of the generic for loop.

Is array forEach faster than for loop?

The FOR loop without length caching and FOREACH work slightly faster on arrays than FOR with length caching. Array. Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays.

Which one is faster for or forEach in 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.

Why is forEach slower?

ForEach is 96% slower than for loop. Thanks in advance. It's probably because forEach requires a function call for each element. That doesn't quite explain why it's 96% faster though, you'd expect 50% since you make 1 function call instead of 2 for each element.


1 Answers

AngularJS forEach used to implement ES5 forEach if available, which was not the fastest, but since this commit it is using the fastest for loop.

https://angularjs.de/buecher/angularjs-cookbook/es5-array-functions

If you look at this comparison, you see, that the ES5 forEach implementation is not the fastest. The AngularJS version in this comparison uses ES5 forEach, if it’s available. This is changed by this commit. Now it’s always using the fastest for loop.

  • https://jsperf.com/angular-foreach-vs-native-for-loop/148
like image 174
bfmags Avatar answered Oct 17 '22 13:10

bfmags