Skip to content

Commit

Permalink
events: improve on() performance
Browse files Browse the repository at this point in the history
  • Loading branch information
mscdex committed May 23, 2017
1 parent 8366e7e commit d3e3ade
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 12 deletions.
18 changes: 10 additions & 8 deletions benchmark/events/ee-add-remove.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,26 @@
var common = require('../common.js');
var events = require('events');

var bench = common.createBenchmark(main, {n: [25e4]});
var bench = common.createBenchmark(main, {n: [25e4], listeners: [10]});

function main(conf) {
var n = conf.n | 0;
var listeners = conf.listeners | 0;

var ee = new events.EventEmitter();
var listeners = [];
ee.setMaxListeners(listeners + 1);
var fns = [];

var k;
for (k = 0; k < 10; k += 1)
listeners.push(function() {});
for (k = 0; k < listeners; k += 1)
fns.push(function() { return 0; });

bench.start();
for (var i = 0; i < n; i += 1) {
for (k = listeners.length; --k >= 0; /* empty */)
ee.on('dummy', listeners[k]);
for (k = listeners.length; --k >= 0; /* empty */)
ee.removeListener('dummy', listeners[k]);
for (k = listeners; --k >= 0; /* empty */)
ee.on('dummy', fns[k]);
for (k = listeners; --k >= 0; /* empty */)
ee.removeListener('dummy', fns[k]);
}
bench.end(n);
}
8 changes: 4 additions & 4 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,10 @@ EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
};

function $getMaxListeners(that) {
if (that._maxListeners === undefined)
const maxListeners = that._maxListeners;
if (maxListeners === undefined)
return EventEmitter.defaultMaxListeners;
return that._maxListeners;
return maxListeners;
}

EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
Expand Down Expand Up @@ -230,7 +231,6 @@ EventEmitter.prototype.emit = function emit(type) {
};

function _addListener(target, type, listener, prepend) {
var m;
var events;
var existing;

Expand Down Expand Up @@ -275,7 +275,7 @@ function _addListener(target, type, listener, prepend) {

// Check for listener leak
if (!existing.warned) {
m = $getMaxListeners(target);
const m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
const w = new Error('Possible EventEmitter memory leak detected. ' +
Expand Down

0 comments on commit d3e3ade

Please sign in to comment.