I wanted to compare JS EventEmitter and RxJS performance. I wrote following benchmark script to do that:
Performance Test
import Rx from 'rxjs/Rx';
import Kefir from 'kefir';
import { EventEmitter } from "events";
let Benchmark = require ("benchmark");
let suite = new Benchmark.Suite;
suite
.add('for', () => {
let numArray = [1,2,3,4,5,6,7,8,9,10];
let count = 0;
for (let i = 0; i<numArray.length; i++)
count += numArray[i];
})
.add('forEach', () => {
let numArray = [1,2,3,4,5,6,7,8,9,10];
let count = 0;
numArray.forEach((num) => { count += num; });
})
.add('eventEmitter', () => {
let numArray = [1,2,3,4,5,6,7,8,9,10];
let count = 0;
let myEmitter = new EventEmitter();
myEmitter.on('number', (num) => { count += num; });
numArray.forEach((num) => { myEmitter.emit('number', num); });
})
.add('rxjs', () => {
let numArray = [1,2,3,4,5,6,7,8,9,10];
let count = 0;
let source = Rx.Observable.from(numArray)
.do((x) => { count += x }, (error) => {}, () => {});
source.subscribe((x) => {}, (error) => {}, () => {});
})
.add('kefir', () => {
let numArray = [1,2,3,4,5,6,7,8,9,10];
let count = 0;
let stream = Kefir.sequentially(0, numArray);
count = stream.scan(sum => sum + 1, 0);
})
.on('cycle', function (event) {
console.log(String(event.target));
})
.on('complete', function () {
console.log('Slowest is ' + this.filter('slowest').map('name'));
})
.run({'async': true});
Performance Results
for x 47,595,916 ops/sec ±1.58% (87 runs sampled)
forEach x 4,428,485 ops/sec ±0.75% (86 runs sampled)
eventEmitter x 1,478,876 ops/sec ±0.61% (86 runs sampled)
rxjs x 547,732 ops/sec ±0.66% (86 runs sampled)
kefir x 496,709 ops/sec ±5.15% (50 runs sampled)
Slowest is kefir
As you can see Kefir turned out to be slowest contrary to the claim made at this link.
- Have I done something wrong in writing the test?
- It would be great if anyone can explain the difference why does it occur. Specially when you compare it with javascript event-emitter.