10

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.

1
  • 2
    Array#forEach works without library. Commented Jun 17, 2016 at 7:15

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

5 Comments

The site is in maintenance can you give me any other link.
@bfmags , are you sure it's using ES5 forEach? Looking at the source code for v1.5.7 github.com/angular/angular.js/blob/v1.5.7/src/Angular.js#L237 Line 248 in particular is interesting. If the object is an array, it does not use any native forEach function. It's instead using a for loop. Only if the object is not an array (or array-like), will execution flow to line 255 which will rely on a forEach function on the object.
@Snixtor Updated! It used to use ES5 forEach if available, but now it’s always using the fastest for loop. thnx!
@rittam The community (me and bfmags) have worked together to craft a quality answer to your question. It's been upvoted a few times, meaning that others think it is a useful answer. You should consider marking it as 'the answer', or clarify why you don't think it answers your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.