Higher order Array functions such as filter, map and reduce is great for functional programming, but they can incur PERFO Rmance problems.
varary = [1,2,3,4,5,6];varres = Ary.filter (function(x, I, arr) {Console.log ("Filter:" +x); Console.log ("Create new array:" + (arr = = =ary)); returnX%2==0;}). Map (function(x, I, arr) {Console.log ("Map:" +x); returnx+ "!";}). Reduce (function(r, X, I, arr) {Console.log ("Reduce:" +x); returnr+x;}); Console.log (res);/*"Filter:1" "Create New Array:true" "Filter:2" "Create New Array:true" "Filter:3" "Create New Array:true" "Filter:4" "C reate new Array:true "" Filter:5 "" Create New Array:true "" Filter:6 "" Create New Array:true "" Map:2 "" Map:4 "" Map:6 "Reduc e:4! "" reduce:6! "" 2!4!6! "*/
In the example, filter & Map function would return a new array. That's good because it pushes forward the idea of immutability. However, it's bad because that means I ' m allocating a new array. I ' m iterating over it only once, and then I ' ve got to garbage-collect it later. This could get really expensive if you're dealing with very large source arrays or you ' re doing this quite often.
Using RxJS:
varSource = Rx.Observable.fromArray ([1,2,3,4,5,6]); Source.filter (function(x) {Console.log ("Filter:" +x); returnX%2==0;}). Map (function(x) {Console.log ("Map:" +x); returnx+ "!";}). Reduce (function(r, x) {Console.log ("Reduce:" +x); returnr+x;}). Subscribe (function(res) {Console.log (res);});
/* "Filter:1" "Filter:2" "Map:2" "Filter:3" "Filter:4" "Map:4" "reduce:4!" " Filter:5 "" Filter:6 "" Map:6 "" reduce:6! "" 2!4!6! " */
The biggest thing is so now you'll see it goes through each – the filter, the map, and the reduce-at each step.
Differences:
The first example:it creates and intermediary arrays (during filter and map). Those arrays needed to is iterated over each time, and now they ' ll also has to be garbage-collected.
The RxJS example:it takes every item all the the-the-through to the end without creating any intermediary arrays.
[RxJS] Stream processing with RxJS vs Array Higher-order Functions