-5

This question already has an answer here:

I have a dynamic array that can often be empty, and I need to iterate over all its elements.

So far I have such code:

array.forEach(function(item, index) {
    //stuff here
});

It works fine of course, but I wonder if there is any overhead for the forEach method when the array is empty, in such case maybe better checking first, e.g.

if (array.length > 0) {
    array.forEach(function(item, index) {
        //stuff here
    });
}

Which is better practice?

marked as duplicate by gnat, Andy, Laiv, Eric King, Robert Harvey Jan 3 '18 at 16:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 9
    That's micro-optimization. I would avoid it. It has a cost; the developer coming after you is going to ask "why did he put that there?" If you were in a very tight performance-sensitive loop, or you had run a profiler, then I might consider it, but you aren't, and you didn't. – Robert Harvey Jan 3 '18 at 16:00
  • 3
    @RobertHarvey It might even be a micro-pessimisation. I prefer the first version anyhow, "For each of these zero items" doesn't bother me – Caleth Jan 3 '18 at 16:03
  • 3
    @RobertHarvey and you add the overhead of checking the length every time this code executes. Even if this is an effective micro-optimization (which I doubt) it only helps if the array is often empty. – JimmyJames Jan 3 '18 at 16:03
  • the second option only makes sense if we were checking nulls. – Laiv Jan 3 '18 at 16:12
  • @JimmyJames actually yes, the code runs over many arrays, around 100, and in practice about 90% of them are empty. It probably doesn't change anything though. – Shadow Wizard Jan 3 '18 at 17:59
0

In practice it will depend on the JavaScript executor how it handles it.

The check should effectively be done by the forEach as it has to check for the end in some way, anyway so you are duplicating the check for an empty array and adding its (minimal) overhead for non-empty ones. So, you are probably adding extra CPU cycles.

In general, only do this type of change if a profiler has indicated that a lot of time is spent on the operation.

Not the answer you're looking for? Browse other questions tagged or ask your own question.