diff options
author | Jo Liss <joliss42@gmail.com> | 2014-01-22 02:24:58 +0400 |
---|---|---|
committer | Trevor Norris <trev.norris@gmail.com> | 2014-01-22 05:00:56 +0400 |
commit | b9bec2031e5f44f47cf01c3ec466ab8cddfa94f6 (patch) | |
tree | eb7f24f989f73e377da66d24872e825cacac311f /lib/path.js | |
parent | cdde9a386aca90ae151be9ad9455d0d0586d113b (diff) |
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>
Diffstat (limited to 'lib/path.js')
-rw-r--r-- | lib/path.js | 31 |
1 files changed, 22 insertions, 9 deletions
diff --git a/lib/path.js b/lib/path.js index aabb80df98f..768c4c1e5bc 100644 --- a/lib/path.js +++ b/lib/path.js @@ -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 = '.'; @@ -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); }; |