Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
events: optimize condition for optimal scenario
Instead of always checking whether we've already warned about a
possible EventEmitter memory leak, first run the rest of the
code as accessing random properties on an Array is expensive.
  • Loading branch information
apapirovski committed May 1, 2018
commit 282749f26e2cd4b9b9c064242eef4ec2fbc82353
2 changes: 1 addition & 1 deletion benchmark/events/ee-add-remove.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
const common = require('../common.js');
const events = require('events');

const bench = common.createBenchmark(main, { n: [25e4] });
const bench = common.createBenchmark(main, { n: [1e6] });

function main({ n }) {
const ee = new events.EventEmitter();
Expand Down
30 changes: 14 additions & 16 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,22 +235,20 @@ function _addListener(target, type, listener, prepend) {
}

// Check for listener leak
if (!existing.warned) {
m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m) {
existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
const w = new Error('Possible EventEmitter memory leak detected. ' +
`${existing.length} ${String(type)} listeners ` +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
process.emitWarning(w);
}
m = $getMaxListeners(target);
if (m && m > 0 && existing.length > m && !existing.warned) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you have time and inclination to test: does reducing m && m > 0 to m > 0 make a difference?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if it makes a difference yet but it seems a harmless change and simplifies the conditional further. I don't see why we shouldn't do it.

existing.warned = true;
// No error code for this since it is a Warning
// eslint-disable-next-line no-restricted-syntax
const w = new Error('Possible EventEmitter memory leak detected. ' +
`${existing.length} ${String(type)} listeners ` +
'added. Use emitter.setMaxListeners() to ' +
'increase limit');
w.name = 'MaxListenersExceededWarning';
w.emitter = target;
w.type = type;
w.count = existing.length;
process.emitWarning(w);
}
}

Expand Down