lib: optimize require() path walking
authorBen Noordhuis <info@bnoordhuis.nl>
Tue, 9 Dec 2014 17:57:43 +0000 (18:57 +0100)
committerBen Noordhuis <info@bnoordhuis.nl>
Tue, 9 Dec 2014 21:11:46 +0000 (22:11 +0100)
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: https://github.com/iojs/io.js/pull/130
Reviewed-by: Chris Dickinson <christopher.s.dickinson@gmail.com>
lib/module.js

index 8662b4e..3eb3d3c 100644 (file)
@@ -121,7 +121,7 @@ function tryPackage(requestPath, exts) {
   if (!pkg) return false;
 
   var filename = path.resolve(requestPath, pkg);
-  return tryFile(filename) || tryExtensions(filename, exts) ||
+  return tryFile(filename, null) || tryExtensions(filename, exts) ||
          tryExtensions(path.resolve(filename, 'index'), exts);
 }
 
@@ -131,8 +131,8 @@ function tryPackage(requestPath, exts) {
 Module._realpathCache = {};
 
 // check if the file exists and is not a directory
-function tryFile(requestPath) {
-  var stats = statPath(requestPath);
+function tryFile(requestPath, stats) {
+  stats = stats || statPath(requestPath);
   if (stats && !stats.isDirectory()) {
     return fs.realpathSync(requestPath, Module._realpathCache);
   }
@@ -142,7 +142,7 @@ function tryFile(requestPath) {
 // given a path check a the file exists with any of the set extensions
 function tryExtensions(p, exts) {
   for (var i = 0, EL = exts.length; i < EL; i++) {
-    var filename = tryFile(p + exts[i]);
+    var filename = tryFile(p + exts[i], null);
 
     if (filename) {
       return filename;
@@ -174,7 +174,7 @@ Module._findPath = function(request, paths) {
     if (!trailingSlash) {
       var stats = statPath(basePath);
       // try to join the request to the path
-      filename = tryFile(basePath);
+      filename = tryFile(basePath, stats);
 
       if (!filename && stats && stats.isDirectory()) {
         filename = tryPackage(basePath, exts);