Skip to content

Commit c9dfc2d

Browse files
lencioniljharb
authored andcommitted
[Performance] 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. Fixes #2671.
1 parent ef9a512 commit c9dfc2d

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

Diff for: lib/util/version.js

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

17+
let cachedDetectedReactVersion;
1718
function detectReactVersion() {
19+
if (cachedDetectedReactVersion) {
20+
return cachedDetectedReactVersion;
21+
}
22+
1823
try {
1924
const reactPath = resolve.sync('react', {basedir: process.cwd()});
2025
const react = require(reactPath); // eslint-disable-line global-require, import/no-dynamic-require
21-
return react.version;
26+
cachedDetectedReactVersion = react.version;
27+
return cachedDetectedReactVersion;
2228
} catch (e) {
2329
if (e.code === 'MODULE_NOT_FOUND') {
2430
if (!warnedForMissingVersion) {
2531
error('Warning: React version was set to "detect" in eslint-plugin-react settings, '
2632
+ 'but the "react" package is not installed. Assuming latest React version for linting.');
2733
warnedForMissingVersion = true;
2834
}
29-
return '999.999.999';
35+
cachedDetectedReactVersion = '999.999.999';
36+
return cachedDetectedReactVersion;
3037
}
3138
throw e;
3239
}

0 commit comments

Comments
 (0)