博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[RxJS] Stream Processing With RxJS vs Array Higher-Order Functions
阅读量:5167 次
发布时间:2019-06-13

本文共 2042 字,大约阅读时间需要 6 分钟。

Higher order Array functions such as filter, map and reduce are great for functional programming, but they can incur performance problems.

 

var ary = [1,2,3,4,5,6];var res = ary.filter(function(x, i, arr){  console.log("filter: " + x);  console.log("create new array: " + (arr === ary));  return x%2==0;}).map(function(x, i, arr){  console.log("map: " + x);  return x+"!";}).reduce(function(r, x, i, arr){  console.log("reduce: " + x);  return r+x;});console.log(res);/*"filter: 1""create new array: true""filter: 2""create new array: true""filter: 3""create new array: true""filter: 4""create new array: true""filter: 5""create new array: true""filter: 6""create new array: true""map: 2""map: 4""map: 6""reduce: 4!""reduce: 6!""2!4!6!"*/

 

In the example, filter & map function will 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:

var source = Rx.Observable.fromArray([1,2,3,4,5,6]);source.filter(function(x){  console.log("filter: " + x);  return x%2==0;}).map(function(x){  console.log("map: " + x);  return x+"!";}).reduce(function(r, x){  console.log("reduce: " + x);  return r+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 that now you'll see it goes through each -- the filter, the map, and the reduce -- at each step.

 

Differences:

The first example: it creates two intermediary arrays (during filter and map). Those arrays needed to be iterated over each time, and now they'll also have to be garbage-collected.

The RxJS example:  it takes every item all the way through to the end without creating any intermediary arrays.

转载于:https://www.cnblogs.com/Answer1215/p/4789718.html

你可能感兴趣的文章
写接口请求类型为get或post的时,参数定义的几种方式,如何用注解(原创)--雷锋...
查看>>
【OpenJ_Bailian - 2287】Tian Ji -- The Horse Racing (贪心)
查看>>
Java网络编程--socket服务器端与客户端讲解
查看>>
List_统计输入数值的各种值
查看>>
学习笔记-KMP算法
查看>>
Timer-triggered memory-to-memory DMA transfer demonstrator
查看>>
跨域问题整理
查看>>
[Linux]文件浏览
查看>>
获取国内随机IP的函数
查看>>
今天第一次写博客
查看>>
江城子·己亥年戊辰月丁丑日话凄凉
查看>>
Spring Mvc模式下Jquery Ajax 与后台交互操作
查看>>
(转)matlab练习程序(HOG方向梯度直方图)
查看>>
『Raid 平面最近点对』
查看>>
【ADO.NET基础-数据加密】第一篇(加密解密篇)
查看>>
STL中的优先级队列priority_queue
查看>>
UE4 使用UGM制作血条
查看>>
浏览器对属性兼容性支持力度查询网址
查看>>
虚拟机长时间不关造成的问题
查看>>
面试整理:Python基础
查看>>