Skip to content

Commit 223d153

Browse files
committed
Cache the result in DEV
In DEV it's somewhat likely that we'll see many logs that add component stacks. This could be slow so we cache the results of previous components.
1 parent fa1a7db commit 223d153

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

packages/shared/ReactComponentStackFrame.js

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,11 @@ export function describeBuiltInComponentFrame(
5353
}
5454

5555
let reentry = false;
56+
let componentFrameCache;
57+
if (__DEV__) {
58+
const PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map;
59+
componentFrameCache = new PossiblyWeakMap();
60+
}
5661

5762
export function describeNativeComponentFrame(
5863
fn: Function,
@@ -63,6 +68,13 @@ export function describeNativeComponentFrame(
6368
return '';
6469
}
6570

71+
if (__DEV__) {
72+
const frame = componentFrameCache.get(fn);
73+
if (frame !== undefined) {
74+
return frame;
75+
}
76+
}
77+
6678
const control = Error();
6779

6880
reentry = true;
@@ -119,7 +131,13 @@ export function describeNativeComponentFrame(
119131
if (sampleLines[s] !== controlLines[c]) {
120132
// Return the line we found.
121133
// V8 adds a "new" prefix for native classes. Let's remove it to make it prettier.
122-
return '\n' + sampleLines[s - 1].replace(' at new ', ' at ');
134+
const frame = '\n' + sampleLines[s - 1].replace(' at new ', ' at ');
135+
if (__DEV__) {
136+
if (typeof fn === 'function') {
137+
componentFrameCache.set(fn, frame);
138+
}
139+
}
140+
return frame;
123141
}
124142
}
125143
}
@@ -132,7 +150,13 @@ export function describeNativeComponentFrame(
132150
}
133151
// Fallback to just using the name if we couldn't make it throw.
134152
const name = fn ? fn.displayName || fn.name : '';
135-
return name ? describeBuiltInComponentFrame(name) : '';
153+
const syntheticFrame = name ? describeBuiltInComponentFrame(name) : '';
154+
if (__DEV__) {
155+
if (typeof fn === 'function') {
156+
componentFrameCache.set(fn, syntheticFrame);
157+
}
158+
}
159+
return syntheticFrame;
136160
}
137161

138162
const BEFORE_SLASH_RE = /^(.*)[\\\/]/;

0 commit comments

Comments
 (0)