Skip to content

Commit

Permalink
[Performance] use isDirectory to speed up node_modules lookups
Browse files Browse the repository at this point in the history
This is a backport of 4cf8928 and
fa11d48 (browserify#190 and browserify#191) to the 1.x branch.

This offers a small but useful performance improvement by avoiding unnecessary stat calls.
  • Loading branch information
keithamus authored and ljharb committed May 14, 2019
1 parent b502f7c commit d2816d8
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 6 deletions.
10 changes: 8 additions & 2 deletions lib/async.js
Original file line number Diff line number Diff line change
Expand Up @@ -219,8 +219,14 @@ module.exports = function resolve(x, options, callback) {
if (dirs.length === 0) return cb(null, undefined);
var dir = dirs[0];

var file = path.join(dir, x);
loadAsFile(file, opts.package, onfile);
isDirectory(dir, isdir);

function isdir(err, isdir) {
if (err) return cb(err);
if (!isdir) return processDirs(cb, dirs.slice(1));
var file = path.join(dir, x);
loadAsFile(file, opts.package, onfile);
}

function onfile(err, m, pkg) {
if (err) return cb(err);
Expand Down
10 changes: 6 additions & 4 deletions lib/sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,12 @@ module.exports = function (x, options) {
var dirs = nodeModulesPaths(start, opts, x);
for (var i = 0; i < dirs.length; i++) {
var dir = dirs[i];
var m = loadAsFileSync(path.join(dir, '/', x));
if (m) return m;
var n = loadAsDirectorySync(path.join(dir, '/', x));
if (n) return n;
if (isDirectory(dir)) {
var m = loadAsFileSync(path.join(dir, '/', x));
if (m) return m;
var n = loadAsDirectorySync(path.join(dir, '/', x));
if (n) return n;
}
}
}
};
2 changes: 2 additions & 0 deletions test/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ test('mock package', function (t) {

var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;

function opts(basedir) {
return {
Expand Down Expand Up @@ -142,6 +143,7 @@ test('mock package from package', function (t) {

var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;

function opts(basedir) {
return {
Expand Down
1 change: 1 addition & 0 deletions test/mock_sync.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ test('mock package', function (t) {

var dirs = {};
dirs[path.resolve('/foo')] = true;
dirs[path.resolve('/foo/node_modules')] = true;

function opts(basedir) {
return {
Expand Down

0 comments on commit d2816d8

Please sign in to comment.