Skip to content

Instantly share code, notes, and snippets.

@fbadiola
Created September 1, 2020 10:35
Show Gist options
  • Save fbadiola/272be2565214d7fd744d1e4dac863a4c to your computer and use it in GitHub Desktop.
Save fbadiola/272be2565214d7fd744d1e4dac863a4c to your computer and use it in GitHub Desktop.
Shared Emitter

Results:

shared {
  max: 719.9340949952602,
  min: 44.935156017541885,
  avg: 398.34632273739555
}
const { EventEmitter } = require('events');
const { performance } = require('perf_hooks')
class SharedEmitter {
constructor(rootEmitter = new EventEmitter()) {
this._rootEmitter = rootEmitter;
}
emit(...args) {
return this._rootEmitter.emit(...args);
}
once(...args) {
return this._rootEmitter.once(...args);
}
}
function measurementStats(arr) {
const result = arr.reduce((memo, n) => {
return {
max: Math.max(memo.max, n),
min: Math.min(memo.min, n),
sum: memo.sum + n,
}
}, {
max: -Infinity,
min: Infinity,
sum: 0,
});
result.avg = result.sum / arr.length;
delete result.sum;
return result;
}
function future() {
let resolve, reject, promise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return {
resolve,
reject,
promise,
};
}
const rootEmitter = new SharedEmitter();
const sharedA = new SharedEmitter(rootEmitter);
const sharedB = new SharedEmitter(rootEmitter);
const channels = [
['shared', sharedA, sharedB],
];
const ITERATIONS = 1e6;
async function main() {
for (const [key, src, first] of channels) {
const iterationTimes = [];
for (let i = 0; i < ITERATIONS; i++) {
const f = future();
const start = performance.now();
src.once('trade', () => {
iterationTimes.push(performance.now(start))
f.resolve();
});
src.emit('trade', { ok: true });
await f.promise;
}
const results = measurementStats(iterationTimes);
console.log(key, results);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment