Skip to content

Commit ddf17f9

Browse files
committed
lib: optimize require() path walking
Remove a speed bump from commit 36777d2 by reusing the result of the previous stat() system call. It's a code path that gets called many thousands of times at startup in most applications so shaving off an extra system call can have an appreciable impact on startup times. PR-URL: #130 Reviewed-by: Chris Dickinson <christopher.s.dickinson@gmail.com>
1 parent 535fec8 commit ddf17f9

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

lib/module.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ function tryPackage(requestPath, exts) {
121121
if (!pkg) return false;
122122

123123
var filename = path.resolve(requestPath, pkg);
124-
return tryFile(filename) || tryExtensions(filename, exts) ||
124+
return tryFile(filename, null) || tryExtensions(filename, exts) ||
125125
tryExtensions(path.resolve(filename, 'index'), exts);
126126
}
127127

@@ -131,8 +131,8 @@ function tryPackage(requestPath, exts) {
131131
Module._realpathCache = {};
132132

133133
// check if the file exists and is not a directory
134-
function tryFile(requestPath) {
135-
var stats = statPath(requestPath);
134+
function tryFile(requestPath, stats) {
135+
stats = stats || statPath(requestPath);
136136
if (stats && !stats.isDirectory()) {
137137
return fs.realpathSync(requestPath, Module._realpathCache);
138138
}
@@ -142,7 +142,7 @@ function tryFile(requestPath) {
142142
// given a path check a the file exists with any of the set extensions
143143
function tryExtensions(p, exts) {
144144
for (var i = 0, EL = exts.length; i < EL; i++) {
145-
var filename = tryFile(p + exts[i]);
145+
var filename = tryFile(p + exts[i], null);
146146

147147
if (filename) {
148148
return filename;
@@ -174,7 +174,7 @@ Module._findPath = function(request, paths) {
174174
if (!trailingSlash) {
175175
var stats = statPath(basePath);
176176
// try to join the request to the path
177-
filename = tryFile(basePath);
177+
filename = tryFile(basePath, stats);
178178

179179
if (!filename && stats && stats.isDirectory()) {
180180
filename = tryPackage(basePath, exts);

0 commit comments

Comments
 (0)