From a9c0e6bd13e8686811dcbc6ab52da0ca81225de6 Mon Sep 17 00:00:00 2001 From: Mikhail Bodrov Date: Wed, 1 May 2019 19:55:20 +0300 Subject: [PATCH] Cache checked files in fs (#8388) * Cache checked files in fs * Cache checked dirs in fs * Refactoring isfile * Add to change.md * Use unem instead of const * Update changelog --- CHANGELOG.md | 1 + packages/jest-resolve/src/defaultResolver.ts | 57 ++++++++++++-------- 2 files changed, 35 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6391a1227bfa..e8ed064057cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -37,6 +37,7 @@ ### Performance - `[jest-runtime]` Fix module registry memory leak ([#8282](https://github.com/facebook/jest/pull/8282)) +- `[jest-resolve]` optimize resolve module path ([#8388](https://github.com/facebook/jest/pull/8388)) ## 24.7.1 diff --git a/packages/jest-resolve/src/defaultResolver.ts b/packages/jest-resolve/src/defaultResolver.ts index 44d94620b2b6..8a2e4c9d8c15 100644 --- a/packages/jest-resolve/src/defaultResolver.ts +++ b/packages/jest-resolve/src/defaultResolver.ts @@ -142,39 +142,50 @@ function resolveSync( } } -/* - * helper functions - */ -function isFile(file: Config.Path): boolean { - let result; +enum IPathType { + FILE = 1, + DIRECTORY = 2, + OTHER = 3, +} +const checkedPaths = new Map(); +function statSyncCached(path: string): number { + const result = checkedPaths.get(path); + if (result !== undefined) { + return result; + } + let stat; try { - const stat = fs.statSync(file); - result = stat.isFile() || stat.isFIFO(); + stat = fs.statSync(path); } catch (e) { - if (!(e && e.code === 'ENOENT')) { + if (!(e && (e.code === 'ENOENT' || e.code === 'ENOTDIR'))) { throw e; } - result = false; } - return result; -} - -function isDirectory(dir: Config.Path): boolean { - let result; - - try { - const stat = fs.statSync(dir); - result = stat.isDirectory(); - } catch (e) { - if (!(e && (e.code === 'ENOENT' || e.code === 'ENOTDIR'))) { - throw e; + if (stat) { + if (stat.isFile() || stat.isFIFO()) { + checkedPaths.set(path, IPathType.FILE); + return IPathType.FILE; + } else if (stat.isDirectory()) { + checkedPaths.set(path, IPathType.DIRECTORY); + return IPathType.DIRECTORY; } - result = false; } - return result; + checkedPaths.set(path, IPathType.OTHER); + return IPathType.OTHER; +} + +/* + * helper functions + */ +function isFile(file: Config.Path): boolean { + return statSyncCached(file) === IPathType.FILE; +} + +function isDirectory(dir: Config.Path): boolean { + return statSyncCached(dir) === IPathType.DIRECTORY; } function isCurrentDirectory(testPath: Config.Path): boolean {