Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Commit

Permalink
path: improve POSIX path.join() performance
Browse files Browse the repository at this point in the history
Performance gains are ~4x (~1.5us), but still much slower than a naive
approach. There is some duplicate work done between join(), normalize()
and normalizeArray() so additional optimizations are possible.

Note that this only improves the POSIX implementation.

Thanks to @isaacs and @othiym23 for helping with this optimization.

Signed-off-by: Trevor Norris <trev.norris@gmail.com>
  • Loading branch information
joliss authored and trevnorris committed Jan 22, 2014
1 parent cdde9a3 commit b9bec20
Showing 1 changed file with 22 additions and 9 deletions.
31 changes: 22 additions & 9 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -348,12 +348,17 @@ if (isWindows) {
// posix version
exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path),
trailingSlash = path.substr(-1) === '/';
trailingSlash = path[path.length - 1] === '/',
segments = path.split('/'),
nonEmptySegments = [];

// Normalize the path
path = normalizeArray(path.split('/').filter(function(p) {
return !!p;
}), !isAbsolute).join('/');
for (var i = 0; i < segments.length; i++) {
if (segments[i]) {
nonEmptySegments.push(segments[i]);
}
}
path = normalizeArray(nonEmptySegments, !isAbsolute).join('/');

if (!path && !isAbsolute) {
path = '.';
Expand All @@ -372,13 +377,21 @@ if (isWindows) {

// posix version
exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0);
return exports.normalize(paths.filter(function(p, index) {
if (!util.isString(p)) {
var path = '';
for (var i = 0; i < arguments.length; i++) {
var segment = arguments[i];
if (!util.isString(segment)) {
throw new TypeError('Arguments to path.join must be strings');
}
return p;
}).join('/'));
if (segment) {
if (!path) {
path += segment;
} else {
path += '/' + segment;
}
}
}
return exports.normalize(path);
};


Expand Down

0 comments on commit b9bec20

Please sign in to comment.