Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are native array functions are so much slower then loop [duplicate]

Tags:

The question is in the title, but here is a longer explanation.

Long time ago I learned some nice javascript functions like reduce, filter, map and so on. I really liked them and started to use them frequently (they look stylish and I thought that because they are native functions they should be faster than my old for loops).

Recently I needed to perform some heavy js computations, so I decided to check how faster are they and to my surprise they are not faster, they are much much slower (from 3 to 25 times slower)

Also I have not checked for every function by here are my jsperf tests for:

  • filter (25 times slower)
  • reduce (3 times slower)
  • map (3 times slower)

So why are native functions are so much slower then old loops and what was the point of creating them if they are not doing anything better.

I assume that the speed loss is due to the invocation of the function inside of them, but still it does not justify such loss. Also I can not see why the code written with these functions is more readable, not to mention, that they are not supported in every browser.

like image 783
Salvador Dali Avatar asked Feb 13 '14 08:02

Salvador Dali


People also ask

Is array find faster than for loop?

Library: Benchmark. js. To our surprise, for-loops are much faster than the Array.

Why for loop is faster than forEach in JavaScript?

ForEach is 96% slower than for loop. Thanks in advance. It's probably because forEach requires a function call for each element. That doesn't quite explain why it's 96% faster though, you'd expect 50% since you make 1 function call instead of 2 for each element.

Is for each loop slower than for loop?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

Is map faster than for loop JavaScript?

map() works way faster than for loop.


1 Answers

I think at some point it comes down to the fact that these native functions are more sugar than they are optimizations.

It's not the same as say using Array.prototype.splice rather than looping over and doing it yourself where the implementation is obviously going to be able to do far more under the hood (in memory) than you yourself would be able to.

At some point in time with filter, reduce and map the browser is going to have to loop over your array and perform some operation on the value contained within it (just as you do with a loop). It can't reduce the amount it has to do to achieve the same ends (it's still looping and performing an operation) but it can give you a more pleasing API and provide error checking etc that will increase the time.

like image 120
Dormouse Avatar answered Sep 28 '22 05:09

Dormouse