Skip to content

Commit b8e91a5

Browse files
committed
Cache detected React version
I've been timing and profiling ESLint runs at Airbnb and noticed that react/no-unknown-property is particularly slow for us when using the "detect" setting for React version. When running ESLint using TIMING=1 on a directory that contains about 500 files to be linted in it, react/no-unknown-property shows up as taking about 1700ms. Looking at the callstacks in the profiler, it seems that when this rule calls getStandardName for every JSXAttribute here, it will actually do all of the work to detect the React version every time to determine the correct set of DOM property names. Since there may be a lot of JSXAttribute nodes in a codebase, this adds up to quite a bit of work. By specifying the react version in our ESLint config, the no-unkown-property rule drops out of the top 10 slowest rules entirely, with the 10th slowest clocking in at 180ms. I think it would be a good idea to cache the React version when using detect instead of looking it up every time.
1 parent ef9a512 commit b8e91a5

File tree

2 files changed

+17
-3
lines changed

2 files changed

+17
-3
lines changed

Diff for: lib/util/version.js

+16-3
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,31 @@ function resetWarningFlag() {
1414
warnedForMissingVersion = false;
1515
}
1616

17+
let cachedDetectedReactVersion;
18+
19+
function resetDetectedVersion() {
20+
cachedDetectedReactVersion = undefined;
21+
}
22+
1723
function detectReactVersion() {
24+
if (cachedDetectedReactVersion) {
25+
return cachedDetectedReactVersion;
26+
}
27+
1828
try {
1929
const reactPath = resolve.sync('react', {basedir: process.cwd()});
2030
const react = require(reactPath); // eslint-disable-line global-require, import/no-dynamic-require
21-
return react.version;
31+
cachedDetectedReactVersion = react.version;
32+
return cachedDetectedReactVersion;
2233
} catch (e) {
2334
if (e.code === 'MODULE_NOT_FOUND') {
2435
if (!warnedForMissingVersion) {
2536
error('Warning: React version was set to "detect" in eslint-plugin-react settings, '
2637
+ 'but the "react" package is not installed. Assuming latest React version for linting.');
2738
warnedForMissingVersion = true;
2839
}
29-
return '999.999.999';
40+
cachedDetectedReactVersion = '999.999.999';
41+
return cachedDetectedReactVersion;
3042
}
3143
throw e;
3244
}
@@ -116,5 +128,6 @@ function testFlowVersion(context, methodVer) {
116128
module.exports = {
117129
testReactVersion,
118130
testFlowVersion,
119-
resetWarningFlag
131+
resetWarningFlag,
132+
resetDetectedVersion
120133
};

Diff for: tests/util/version.js

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ describe('Version', () => {
1616
sinon.stub(console, 'error');
1717
expectedErrorArgs = [];
1818
versionUtil.resetWarningFlag();
19+
versionUtil.resetDetectedVersion();
1920
});
2021

2122
afterEach(() => {

0 commit comments

Comments
 (0)