From 4e84f8377cf3f6477e29048a28c9fd4344e23965 Mon Sep 17 00:00:00 2001 From: jdecroock Date: Fri, 4 Oct 2024 10:34:28 +0200 Subject: [PATCH 1/2] Context consumer unmounting perf --- src/create-context.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/create-context.js b/src/create-context.js index 190797b595..bbe1444b55 100644 --- a/src/create-context.js +++ b/src/create-context.js @@ -43,7 +43,11 @@ export function createContext(defaultValue, contextId) { let old = c.componentWillUnmount; c.componentWillUnmount = () => { if (subs) { - subs.splice(subs.indexOf(c), 1); + if (subs.length === 1) { + subs = []; + } else { + subs[subs.indexOf(c)] = subs.pop(); + } } if (old) old.call(c); }; From 57fa02b82e26798bf6ce2f97384389ace0de1323 Mon Sep 17 00:00:00 2001 From: jdecroock Date: Fri, 4 Oct 2024 10:38:01 +0200 Subject: [PATCH 2/2] Test perf of Set based alternative --- src/create-context.js | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/create-context.js b/src/create-context.js index bbe1444b55..400d7716b3 100644 --- a/src/create-context.js +++ b/src/create-context.js @@ -18,8 +18,8 @@ export function createContext(defaultValue, contextId) { /** @type {FunctionComponent} */ Provider(props) { if (!this.getChildContext) { - /** @type {Component[] | null} */ - let subs = []; + /** @type {Set | null} */ + let subs = new Set(); let ctx = {}; ctx[contextId] = this; @@ -31,7 +31,7 @@ export function createContext(defaultValue, contextId) { this.shouldComponentUpdate = function (_props) { if (this.props.value !== _props.value) { - subs.some(c => { + subs.forEach(c => { c._force = true; enqueueRender(c); }); @@ -39,15 +39,11 @@ export function createContext(defaultValue, contextId) { }; this.sub = c => { - subs.push(c); + subs.add(c); let old = c.componentWillUnmount; c.componentWillUnmount = () => { if (subs) { - if (subs.length === 1) { - subs = []; - } else { - subs[subs.indexOf(c)] = subs.pop(); - } + subs.delete(c); } if (old) old.call(c); };