Lee Hojin
Lee Hojin

Reputation: 89

Why RxJS operators is faster than Javascript array method to filter and map array with large size?

import { of, from, asyncScheduler } from 'rxjs'; 
import { map, filter } from 'rxjs/operators';

let arr = [];
console.log("A");
console.log(new Date());
for(let i = 0; i < 10000000; i++){
  arr.push(i);
}

console.log("B");
console.log(new Date());

let arr2 = arr.filter(x => x%2 === 0)
  .map(x => x * 3)
  .map(x => x * 3)
  .map(x => x * 3);

console.log("C");
console.log(new Date());
console.log(arr2.length);

const source = from(arr).pipe(
  filter(x => x%2 === 0),
  map(x => x * 3),
  map(x => x * 3),
  map(x => x * 3)
);

console.log("D");
console.log(new Date());

let arr3 = [];

source.subscribe(x => arr3.push(x),
x => {},
() => { console.log("E");console.log(new Date()); }
);

console.log("F");
console.log(new Date());
console.log(arr3.length);

This is my code for test.

I test array filter and map performance between RxJS operators and methods of Javascript array.

For 10,000,000 size array, I did 1 filter and 3 maps.

JS methods takes about 3 seconds (time gap between console log B and C),

but RxJS takes less then 1 second (time gap between console log D and E)

As I check for 100 size array, JS is clearly faster, but for large size array RxJS is faster.

I wonder how RxJS can be faster than native JS implement. Please help me.

https://stackblitz.com/edit/rxjs-7qflvl?devtoolsheight=60

Upvotes: 2

Views: 568

Answers (2)

cuspymd
cuspymd

Reputation: 1088

The test results in my PC are different from yours. I think it may vary depending on PC environment.

  • Chrome v78.0.3904.97 64bit
    • C-B: 521 ms
    • E-D: 818 ms
  • Firefox v70.0 64bit
    • C-B: 369 ms
    • E-D: 493 ms

Below is my PC environment.

  • CPU: Intel i7-8700
  • OS: windows 10 64bit

Upvotes: 1

martin
martin

Reputation: 96979

You actually don't have the same behavior, so that might be the reason why it appears like RxJS is faster.

In particular in this code:

let arr2 = arr.filter(x => x%2 === 0)
  .map(x => x * 3)
  .map(x => x * 3)
  .map(x => x * 3);

With each filter() and map() you're creating a new array of 10M or 5M items. So in this case you create 10M items, then process it with .filter(x => x%2 === 0) that returns a new array of 5M items and so on.

However, RxJS from() will iterate the array only once and never create any new arrays. It will take each item and run it through one filter() and three map() operators which is therefore much more efficient.

Upvotes: 3

Related Questions