Skip to content
Advertisement

Is it faster to use one for-loop or use multiple built-in methods?

So I was recreating the ????-Sigma function in Javascript in two different ways and was wondering, which one of the methods is faster:

JavaScript

However, I’m unsure which will run faster, since with the built-in method, there would have to be two “passes” by both the map and the reduce.

Advertisement

Answer

The function which uses built-in methods can actually be written in even fewer bytes/methods:

JavaScript

After doing some testing in multiple environments with multiple sizes of both inputs and iterations, I can safely say that the method using the for-loop is between 3 and 20 times faster than the built-in methods one.

My code for testing looked something like this:

JavaScript

I tested my code in

All testing was done on an Intel MacBook Air.

Now the question is, why is that?

My hunch is, that while the built-in methods method has a lot more one-liner satisfaction, it has to create an array in memory while the other one doesn’t.

Doing some other performance tests shows that environments above, which struggle with the built-in methods method, also struggle with creating a lot of Arrays in a short amount of time.

The ratio with the initial function isn’t quite as ratio between creating an Array and a number though, so I the Array.prototype.reduce function is definitely more optimized than a for-loop.

Here are some of the ratios I found in different Javascript environments. The numbers created were 6-digits long and the Arrays created were 100 elements long (Both of which are expected when inputting the values for all square numbers from 1 to 100 summed up.)

  • Node: The for-loop method is ~40 faster than the built-in methods method and creating a Number is ~500 times faster than creating an Array.
  • Google Chrome DevTools: The for-loop method is ~30 faster than the built-in methods method and creating a Number is ~50 times faster than creating an Array.
  • Deno: The for-loop method is ~40 faster than the built-in methods method and creating a Number is ~500 times faster than creating an Array.
  • Apple Safari DevTools: The for-loop method is ~4 faster than the built-in methods method and creating a Number is ~400 times faster than creating an Array.

All of those results are very rough because performance depends on so many things.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement