Browse Source

path: improve POSIX path.join() performance

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>
v0.11.11-release
Jo Liss 11 years ago
committed by Trevor Norris
parent
commit
b9bec2031e
  1. 31
      lib/path.js

31
lib/path.js

@ -348,12 +348,17 @@ if (isWindows) {
// posix version // posix version
exports.normalize = function(path) { exports.normalize = function(path) {
var isAbsolute = exports.isAbsolute(path), var isAbsolute = exports.isAbsolute(path),
trailingSlash = path.substr(-1) === '/'; trailingSlash = path[path.length - 1] === '/',
segments = path.split('/'),
nonEmptySegments = [];
// Normalize the path // Normalize the path
path = normalizeArray(path.split('/').filter(function(p) { for (var i = 0; i < segments.length; i++) {
return !!p; if (segments[i]) {
}), !isAbsolute).join('/'); nonEmptySegments.push(segments[i]);
}
}
path = normalizeArray(nonEmptySegments, !isAbsolute).join('/');
if (!path && !isAbsolute) { if (!path && !isAbsolute) {
path = '.'; path = '.';
@ -372,13 +377,21 @@ if (isWindows) {
// posix version // posix version
exports.join = function() { exports.join = function() {
var paths = Array.prototype.slice.call(arguments, 0); var path = '';
return exports.normalize(paths.filter(function(p, index) { for (var i = 0; i < arguments.length; i++) {
if (!util.isString(p)) { var segment = arguments[i];
if (!util.isString(segment)) {
throw new TypeError('Arguments to path.join must be strings'); throw new TypeError('Arguments to path.join must be strings');
} }
return p; if (segment) {
}).join('/')); if (!path) {
path += segment;
} else {
path += '/' + segment;
}
}
}
return exports.normalize(path);
}; };

Loading…
Cancel
Save