From 1c55f8f6903308a9c63c14acf8a1d35523cca687 Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Mon, 10 Jul 2023 18:56:31 +0200 Subject: [PATCH 1/2] perf: use fs.opendir for recursiveReadDirSync --- .../next/src/server/lib/recursive-readdir-sync.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/next/src/server/lib/recursive-readdir-sync.ts b/packages/next/src/server/lib/recursive-readdir-sync.ts index aadcf75dd18c..d74c2c2569a9 100644 --- a/packages/next/src/server/lib/recursive-readdir-sync.ts +++ b/packages/next/src/server/lib/recursive-readdir-sync.ts @@ -13,17 +13,19 @@ export function recursiveReadDirSync( /** Used to replace the initial path, only the relative path is left, it's faster than path.relative. */ rootDir = dir ): string[] { - const result = fs.readdirSync(dir, { withFileTypes: true }) + // Use opendirSync for better memory usage + const result = fs.opendirSync(dir) - result.forEach((part) => { + let part: fs.Dirent | null + while ((part = result.readSync())) { const absolutePath = join(dir, part.name) - if (part.isDirectory()) { recursiveReadDirSync(absolutePath, arr, rootDir) - return + } else { + arr.push(absolutePath.slice(rootDir.length)) } - arr.push(absolutePath.replace(rootDir, '')) - }) + } + result.closeSync() return arr } From 8b22fc9f8000bda5c174b6efdc7762affaef193b Mon Sep 17 00:00:00 2001 From: Shu Ding Date: Mon, 10 Jul 2023 19:01:19 +0200 Subject: [PATCH 2/2] use path.sep --- .../next/src/server/lib/recursive-readdir-sync.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/next/src/server/lib/recursive-readdir-sync.ts b/packages/next/src/server/lib/recursive-readdir-sync.ts index d74c2c2569a9..07549a88bbc3 100644 --- a/packages/next/src/server/lib/recursive-readdir-sync.ts +++ b/packages/next/src/server/lib/recursive-readdir-sync.ts @@ -1,5 +1,5 @@ import fs from 'fs' -import { join } from 'path' +import { sep } from 'path' /** * Recursively read directory @@ -10,19 +10,19 @@ export function recursiveReadDirSync( dir: string, /** This doesn't have to be provided, it's used for the recursion */ arr: string[] = [], - /** Used to replace the initial path, only the relative path is left, it's faster than path.relative. */ - rootDir = dir + /** Used to remove the initial path suffix and leave only the relative, faster than path.relative. */ + rootDirLength = dir.length ): string[] { // Use opendirSync for better memory usage const result = fs.opendirSync(dir) let part: fs.Dirent | null while ((part = result.readSync())) { - const absolutePath = join(dir, part.name) + const absolutePath = dir + sep + part.name if (part.isDirectory()) { - recursiveReadDirSync(absolutePath, arr, rootDir) + recursiveReadDirSync(absolutePath, arr, rootDirLength) } else { - arr.push(absolutePath.slice(rootDir.length)) + arr.push(absolutePath.slice(rootDirLength)) } }