Skip to content

Instantly share code, notes, and snippets.

@g13013
Last active August 29, 2015 14:00
Show Gist options
  • Save g13013/0f0246a181909e259edd to your computer and use it in GitHub Desktop.
Save g13013/0f0246a181909e259edd to your computer and use it in GitHub Desktop.
A benchmark that treats a relative path to a file in the same directory, it shows that node`s `path` and `url` APIs in are not always the fastest way.
var Benchmark = require('benchmark');
var path = require('path');
var url = require('url');
var suite = new Benchmark.Suite();
var p1 = 'path/to/file';
var p2 = './another_file';
function a() {
return path.join(p1, '..', p2);
}
function a1() {
return path.join(p1, '..', p2).replace(/\\/, '/');
}
function a2() {
var dir;
dir = p1.split('/');
dir.pop();
dir.push(p2.replace('./', ''));
return dir.join('/');
}
function a3() {
var base = path.basename(p1);
return p1.replace(base, '') + p2.replace('./', '');
}
function a4() {
return url.resolve('path/to/file', './another_file');
}
//check output
console.log(a(), '-> path.join');
console.log(a1(), '-> path.join with replace with to unix separator:');
console.log(a2(), '-> split');
console.log(a3(), '-> cut');
console.log(a4(), '-> url.resolve');
console.log('');
// add tests
suite
.add('path.join', a)
.add('path.join with replace with to unix separator', a1)
.add('split', a2)
.add('cut', a3)
.add('url.resolve', a4)
// add listeners
.on('cycle', function(event) {
console.log(String(event.target));
})
.on('complete', function() {
console.log('Fastest is ' + this.filter('fastest').pluck('name'));
})
// run async
.run({ 'async': true });
//results:
//
// path/to/another_file -> path.join
// path/to/another_file -> path.join with replace with to unix separator:
// path/to/another_file -> split
// path/to/another_file -> cut
// path/to/another_file -> url.resolve
//
// path.join x 125,439 ops/sec ±20.17% (57 runs sampled)
// path.join with replace with to unix separator x 109,778 ops/sec ±15.86% (67 runs sampled)
// split x 1,577,144 ops/sec ±17.13% (59 runs sampled)
// cut x 559,393 ops/sec ±18.45% (51 runs sampled)
// url.resolve x 18,055 ops/sec ±16.97% (59 runs sampled)
// Fastest is split
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment