0

I was looking at the code in angular 1.3.4 for angular.forEach and it looks like the following...

function forEach(obj, iterator, context) {
  ...
      for (key = 0, length = obj.length; key < length; key++) {
        if (isPrimitive || key in obj) {
          iterator.call(context, obj[key], key, obj);
        }
  ...
  return obj;
}

But according to this link, it is faster to use decrement. So should I switch over to a pure javascript for loop? Why does the Angular team increment if performance is an issue? or is there a way (short of rewriting) to get angular.forEach to do this?

3
  • 1
    The speed difference between counting forwards and counting backwards is largely irrelevant to nearly all of the code running on the web today. Don't focus on these types of optimizations until you've taken care of everything else - and even then, these probably don't merit much attention. Commented Jan 12, 2015 at 22:22
  • I would hazard a guess that users of angular (or any other iterating function, eg jQuery's $.each etc) would expect it to iterate through something in the usual order, ie first item first. Doing otherwise would be rather unexpected. If performance is your main concern, don't go using library based utility functions that are probably doing a bunch of other things you don't need also. Commented Jan 12, 2015 at 22:22
  • I would change your question title and the second of your questions to be less about why angular does something and more about how you might overcome what you see as a shortcoming of their code. Right now the title appears to be asking for an opinion (actually a guess if one is not a member of the Angular team), which is not really a good fit for Stack Overflow. Commented Jan 12, 2015 at 22:29

1 Answer 1

1

I've resorted to using _.forEach instead, Angular's functions are slow (especially angular.copy). As the comments say, the time differences are minimal. But if you're dealing with enterprise amounts of data like I have had to, _.forEach works just fine (it's much better than looking at a nasty old-school for loop). Hope that helps. Here are is a link that tests the JS performance for 'for' loops from multiple libraries.

Here's the link for underscore (i.e. _)

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

1 Comment

ng-repeat is great, I encourage use of it when applicable. No prob!

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.