Commit 5a76601c8fb for nodejs
commit 5a76601c8fbc49e1f7427d0a61d463e4cb1e4539
Author: Roberto Bianchi <roberto.bianchi@spendesk.com>
Date: Wed Nov 25 21:16:12 2026 +0100
events: use indexed appends in eventNames
Collect active event names with indexed writes instead of calling
the primordial push function for each name.
Signed-off-by: Roberto Bianchi <roberto.bianchi@spendesk.com>
PR-URL: https://github.com/nodejs/node/pull/66875
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: James M Snell <jasnell@gmail.com>
diff --git a/benchmark/events/ee-event-names.js b/benchmark/events/ee-event-names.js
new file mode 100644
index 00000000000..9b2ca4ac487
--- /dev/null
+++ b/benchmark/events/ee-event-names.js
@@ -0,0 +1,55 @@
+'use strict';
+
+const common = require('../common');
+const assert = require('node:assert');
+const { EventEmitter } = require('node:events');
+
+const bench = common.createBenchmark(main, {
+ n: [1e6],
+ size: [0, 4, 32],
+ shape: ['strings', 'mixed', 'removed'],
+ mode: ['read', 'churn'],
+});
+
+function main({ n, size, shape, mode }) {
+ const emitter = new EventEmitter();
+ const listener = () => {};
+ const keys = [];
+ for (let index = 0; index < size; index++) {
+ const key = shape === 'mixed' && index % 2 === 0 ?
+ Symbol(`event${index}`) : `event${index}`;
+ emitter.on(key, listener);
+ if (shape === 'removed' && index % 2 === 0) {
+ emitter.removeListener(key, listener);
+ } else {
+ keys.push(key);
+ }
+ }
+ if (mode === 'churn') keys.push('transient');
+ const expected = [
+ ...keys.filter((key) => typeof key === 'string'),
+ ...keys.filter((key) => typeof key === 'symbol'),
+ ];
+ const last = expected[expected.length - 1];
+ let checksum = 0;
+ let result;
+ bench.start();
+ if (mode === 'read') {
+ for (let iteration = 0; iteration < n; iteration++) {
+ result = emitter.eventNames();
+ checksum += result.length;
+ if (result.length !== 0 && result[result.length - 1] === last) checksum++;
+ }
+ } else {
+ for (let iteration = 0; iteration < n; iteration++) {
+ emitter.on('transient', listener);
+ result = emitter.eventNames();
+ checksum += result.length;
+ if (result.length !== 0 && result[result.length - 1] === last) checksum++;
+ emitter.removeListener('transient', listener);
+ }
+ }
+ bench.end(n);
+ assert.deepStrictEqual(result, expected);
+ assert.strictEqual(checksum, n * (expected.length + (expected.length !== 0)));
+}
diff --git a/lib/events.js b/lib/events.js
index 3b6805d8998..23af6aec7b5 100644
--- a/lib/events.js
+++ b/lib/events.js
@@ -877,7 +877,7 @@ EventEmitter.prototype.eventNames = function eventNames() {
for (const key of ReflectOwnKeys(events)) {
// Removed listeners leave the key in place with an `undefined` value.
if (events[key] !== undefined)
- ArrayPrototypePush(names, key);
+ names[names.length] = key;
}
return names;
};