-1

i have write a forEach implemention for understand this Response:

function myForeach(sourch, func) {
    for (var i = 0, len = sourch.length; i < len; i++) {
        func(sourch[i], i, arr);
    }
}

and like forEach, its slow than simple for-loop:

for (var i = 0, len = arr.length; i < len; i++) {
    (function(item) {
        action(item);
    })(arr[i], i, arr); //exactly what foreach dose!
}

here, the two way have function setup & teardown. why the for its so faster?

enter image description here

dovid
  • 6,354
  • 3
  • 33
  • 73
  • 2
    Okay, but reading through the linked post, that seems to answer this already; why are you posting this question? Is there information missing? – Mike 'Pomax' Kamermans Jul 19 '18 at 01:12
  • 2
    @Mike'Pomax'Kamermans Yes. my question its different. i'm Imitating the forEach operation, and still its faster. – dovid Jul 19 '18 at 01:14
  • The code you show is kind of weird (you're invoking a single parameter inner function with three arguments), but from what I can tell the profiler shows that the for loop is faster. Based on the answers you already link to, that is to be expected. Based on interperet basics, that is also to be expected. However, your code shows two cases, and three results, so can you update your question with the complete [mcve] if need an explanation beyond what the answers linked already provide? – Mike 'Pomax' Kamermans Jul 19 '18 at 01:19
  • 1
    @Mike'Pomax'Kamermans Are you sure you've read both of my code snippets well? I use both with a for loop. If you understand the reason, I would be very happy if you would explain it to me. – dovid Jul 19 '18 at 01:25
  • 1
    @Mike'Pomax'Kamermans I try to imitate the Array.forEach, which [invoke the callback with three argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – dovid Jul 19 '18 at 01:29
  • 2
    FWIW, when ran on my FF, "for with function" is around the same as "native for" (98,142 vs 95,886 op/sec). Also, your *myForeach* doesn't do the same as the builtin Array#forEach which includes a check for empty slots. – Kaiido Jul 19 '18 at 01:30

2 Answers2

2

I think it's largely related to the fact that your action() is a no-op which gets optimized away by the runtime in some cases, but not in other cases.

If you change your action to actually do something (e.g. add the array values to a sum variable), the differences are a lot smaller.

Here are my updated benchmark results, also on Chrome:

results

Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
  • Very nice, so interesting! What about the difference that still exists? I am so curious to understand. – dovid Jul 19 '18 at 11:29
0

When declaring an anonymous function in a loop i.e. 'function() { // doStuff}' the interpreter has to define a new function at runtime every iteration of the loop, thus creating alot of overhead for the interpreter.