0
\$\begingroup\$

I was wondering which for loop is less hard on the computer, and why it is

Example:

    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    greet.forEach(function(index){
        console.log(index);
    });

vs

    var greet = ["Hey", "Howdy", "Hello", "Hi"];
    for(var i = 0; i < greet.length; i++) {
        console.log(greet[i]);
    }
\$\endgroup\$
5
\$\begingroup\$

You should not micro-optimize code at this level, unless you have good reason to believe it is a bottleneck in your code. This is for a number of reasons:

1) optimization depends on the particulars of the Javascript runtime. What is fast in node or V8 is not necessarily fast in SpiderMonkey or Chakra.

2) optimization depends on the particulars of your code, how often and in what order you access it, how large the data is, etc.

If the above arguments have not persuaded you that you shouldn't optimize prematurely, you should learn to profile and figure out for yourself which is faster. For example, if I open up node, I can write:

> { 
    var s = 0,  arr = new Array(1000000); 
    console.time("for"); 
    for(var i = 0; i < arr.length; i++) { s += arr[i] }; 
    console.timeEnd("for");
}
for: 35.022ms

> { 
    var s = 0, arr = new Array(1000000); 
    console.time("forEach"); 
    arr.forEach(x => s += x); 
    console.timeEnd("forEach");
}
forEach: 13.610ms

Now, you're thinking: "oh! forEach must be twice as fast as a for loop!. I'll use forEach for everything"

But wait! maybe something is up because arr is a bunch of undefineds. What if we actually initialize the array to a number before running the sum?

> { var s = 0, arr = new Array(1000000); for(var i=0; i<arr.length; i++) arr[i] = i; 
    console.time("forEach"); 
    arr.forEach(x => s += x); 
    console.timeEnd("forEach"); 
    console.log(s) }
forEach: 23.947ms
499999500000

> { var s = 0, arr = new Array(1000000); for(var i=0; i<arr.length; i++) arr[i] = i; 
   console.time("for"); 
   for(var i=0; i<arr.length; i++) { s += arr[i] }; 
   console.timeEnd("for"); 
   console.log(s) }
for: 13.959ms
499999500000

Ahh ... the for loop got much faster and the forEach loop got slower! why? You'll have to dig into the particulars of each runtime's optimization features for the answer.

Summary:

Q) Which loop style is faster?
A) It depends.

Q) Should I spend time optimizing small for-loops
A) no

Q) But how should I know when to optimize?
A) measure it by profiling instead of guessing.

\$\endgroup\$
2
\$\begingroup\$

The indexed for loop is a bit faster (not much, but it is), since the js engine doesn't have to look the properties of the object up before looping through them. It basically does your job when it does the first part.

So to put it into a metaphor, it's like telling someone to look up 50 addresses you gave them instead of telling someone, to look up 50 addresses, that are stored in a safe 3 floors below you.

I did profile it if you're curious.

Details:

I just created an array with 10,000,000 elements, each being equal to its index ([0, 1, 2, 3...]), then added their squares to a number to make sure it doesn't get optimized out. The forEach method came out at an average of 1407ms and the normal for method came out at 1443ms with 20 test runs.

\$\endgroup\$
  • \$\begingroup\$ Can you elaborate on the speed difference &/or include your profiling results? \$\endgroup\$ – Pikalek Apr 27 '18 at 18:21
  • 1
    \$\begingroup\$ @Pikalek there you go \$\endgroup\$ – Bálint Apr 27 '18 at 22:16

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