简体   繁体   中英

Functional or Imperative code for dealing with considerably large array in javascript?

When working with array in javascript what would you choose, functional way or imperative way while imperative is faster than functional. I am so confused.

Here is the jsPerf test i ran with plain for loop and pair of map and filter.

My two cents: In general, I prefer working functional way with arrays, since I find functional methods more flexible and easier to read and maintain.

Especially where the performance are not critical or the there aren't noticeable differences.

Let's say that the functional way takes 50x the times of regular loop. If a regular loop takes 1ms, it means the functional takes 50ms and in most of the case that is still okay.

So I wouldn't sacrifice my code for optimization in that case, especially in application and / or shared repo.

However, when I code videogames, I usually try to do regular loop. Both for performance reasons, but also because in that context usually you have to deal with arrays of bytes, and I find functional programming less flexible.

Said that: in JS the problem of array's method is that they aren't lazy. It means, in your case, you're iterating twice the array because you call two methods ( filter and map ). In other languages (eg Rust) such method are "lazy", and they're not invoked until you actually do something with the iterator: that reduce the performance issue you can have compare to a regular loop.

There are library in JS that supports lazy methods (eg RxJS on observable), so you might want to check those if you're looking for something in the middle (saving a bit of perf while still using a functional approach).

The difference between Array.map and a for-loop is that the for-loop does nothing more than iterating over the values of the array. Within the body of the loop, you can do whatever with these values. Array.map does more than that. It iterates over the array, creating a new array with the value of the callback invoked on every value.

In my opinion you should use a for-loop as much as possible over Array.map , while it is a lot quicker. Use Array.map when you want to create a new array with mutated values in the original array.

Basically these are the same as:

For-loop:

const array = [1, 2, 3];
const mutatedArray = [];

for(let i = 0; i < array.length; i++) {
    let mutatedValue = array[i] * 2;

    mutatedArray.push(mutatedValue);
}

Array.map:

const array = [1, 2, 3];
const mutatedArray = array.map(x => x * 2);

It is a lot cleaner and quicker to write.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM