Skip to content

Commit eb35666

Browse files
committed
process: use SafeSet for finalization refs
Store finalization refs in SafeSet collections instead of arrays. This makes identity-based insertion, deletion, and emptiness checks match how the collections are used. Signed-off-by: Kamat, Trivikram <16024985+trivikr@users.noreply.github.com> Assisted-by: openai:gpt-5.5
1 parent 3c3ccb0 commit eb35666

1 file changed

Lines changed: 14 additions & 17 deletions

File tree

lib/internal/process/finalization.js

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22
// This file is a modified version of the on-exit-leak-free module on npm.
33

44
const {
5-
ArrayPrototypeFilter,
6-
ArrayPrototypeIndexOf,
7-
ArrayPrototypePush,
8-
ArrayPrototypeSplice,
5+
SafeSet,
96
SafeFinalizationRegistry,
107
SafeWeakRef,
118
} = primordials;
@@ -20,8 +17,8 @@ function createFinalization() {
2017

2118
const refs = {
2219
__proto__: null,
23-
exit: [],
24-
beforeExit: [],
20+
exit: new SafeSet(),
21+
beforeExit: new SafeSet(),
2522
};
2623

2724
const functions = {
@@ -31,21 +28,21 @@ function createFinalization() {
3128
};
3229

3330
function install(event) {
34-
if (refs[event].length > 0) {
31+
if (refs[event].size > 0) {
3532
return;
3633
}
3734

3835
process.on(event, functions[event]);
3936
}
4037

4138
function uninstall(event) {
42-
if (refs[event].length > 0) {
39+
if (refs[event].size > 0) {
4340
return;
4441
}
4542

4643
process.removeListener(event, functions[event]);
4744

48-
if (refs.exit.length === 0 && refs.beforeExit.length === 0) {
45+
if (refs.exit.size === 0 && refs.beforeExit.size === 0) {
4946
registry = null;
5047
}
5148
}
@@ -70,14 +67,12 @@ function createFinalization() {
7067
fn(obj, event);
7168
}
7269
}
73-
refs[event] = [];
70+
refs[event].clear();
7471
}
7572

7673
function clear(ref) {
7774
for (const event of ['exit', 'beforeExit']) {
78-
const index = ArrayPrototypeIndexOf(refs[event], ref);
79-
if (index !== -1) {
80-
ArrayPrototypeSplice(refs[event], index, 1);
75+
if (refs[event].delete(ref)) {
8176
uninstall(event);
8277
}
8378
}
@@ -92,7 +87,7 @@ function createFinalization() {
9287
registry ||= new SafeFinalizationRegistry(clear);
9388
registry.register(obj, ref);
9489

95-
ArrayPrototypePush(refs[event], ref);
90+
refs[event].add(ref);
9691
}
9792

9893
/**
@@ -132,10 +127,12 @@ function createFinalization() {
132127
}
133128
registry.unregister(obj);
134129
for (const event of ['exit', 'beforeExit']) {
135-
refs[event] = ArrayPrototypeFilter(refs[event], (ref) => {
130+
for (const ref of refs[event]) {
136131
const _obj = ref.deref();
137-
return _obj && _obj !== obj;
138-
});
132+
if (!_obj || _obj === obj) {
133+
refs[event].delete(ref);
134+
}
135+
}
139136
uninstall(event);
140137
}
141138
}

0 commit comments

Comments
 (0)