Skip to content

Commit 58a65d6

Browse files
apapirovskiMylesBorins
authored andcommitted
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. In addition, remove an unnecessary truthy check. PR-URL: #20452 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Luigi Pinca <[email protected]> Reviewed-By: Ben Noordhuis <[email protected]> Reviewed-By: Ruben Bridgewater <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Tobias Nießen <[email protected]> Reviewed-By: Trivikram Kamat <[email protected]>
1 parent 74685f1 commit 58a65d6

File tree

2 files changed

+15
-17
lines changed

2 files changed

+15
-17
lines changed

benchmark/events/ee-add-remove.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
const common = require('../common.js');
33
const events = require('events');
44

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

77
function main({ n }) {
88
const ee = new events.EventEmitter();

lib/events.js

+14-16
Original file line numberDiff line numberDiff line change
@@ -235,22 +235,20 @@ function _addListener(target, type, listener, prepend) {
235235
}
236236

237237
// Check for listener leak
238-
if (!existing.warned) {
239-
m = $getMaxListeners(target);
240-
if (m && m > 0 && existing.length > m) {
241-
existing.warned = true;
242-
// No error code for this since it is a Warning
243-
// eslint-disable-next-line no-restricted-syntax
244-
const w = new Error('Possible EventEmitter memory leak detected. ' +
245-
`${existing.length} ${String(type)} listeners ` +
246-
'added. Use emitter.setMaxListeners() to ' +
247-
'increase limit');
248-
w.name = 'MaxListenersExceededWarning';
249-
w.emitter = target;
250-
w.type = type;
251-
w.count = existing.length;
252-
process.emitWarning(w);
253-
}
238+
m = $getMaxListeners(target);
239+
if (m > 0 && existing.length > m && !existing.warned) {
240+
existing.warned = true;
241+
// No error code for this since it is a Warning
242+
// eslint-disable-next-line no-restricted-syntax
243+
const w = new Error('Possible EventEmitter memory leak detected. ' +
244+
`${existing.length} ${String(type)} listeners ` +
245+
'added. Use emitter.setMaxListeners() to ' +
246+
'increase limit');
247+
w.name = 'MaxListenersExceededWarning';
248+
w.emitter = target;
249+
w.type = type;
250+
w.count = existing.length;
251+
process.emitWarning(w);
254252
}
255253
}
256254

0 commit comments

Comments
 (0)