Skip to content

Instantly share code, notes, and snippets.

@cxreg
Last active December 15, 2015 19:28
Show Gist options
  • Save cxreg/5311075 to your computer and use it in GitHub Desktop.
Save cxreg/5311075 to your computer and use it in GitHub Desktop.
benchmarking node binary-to-url-encoding
var fs = require('fs');
var re = /(..)/g;
var methods = {
with_escape: function(data, cb) {
cb(escape(data.toString('binary')));
},
with_loop: function (data, cb) {
var buf = '';
for (var n = 0; n < data.length; n++) {
buf += '%' + data[n].toString(16);
}
cb(buf);
},
with_broken_loop: function (data, cb) {
var buf = '', n = 0;
        var rescheds = 0;
var do_chunk = function() {
for (n = n; n < data.length; n++) {
buf += '%' + data[n].toString(16);
// Sometimes, break up the work
if (! (n % 10000)) {
rescheds++;
process.nextTick(do_chunk);
n++; // because for() wont do it with early return
return;
}
}
console.log(rescheds + ' rescheds')
cb(buf);
};
do_chunk();
},
with_regex: function(data, cb) {
cb(data.toString('hex').toUpperCase().replace(/(..)/g, "%$1"));
},
with_regex_lower: function(data, cb) {
cb(data.toString('hex').replace(/(..)/g, "%$1"));
},
with_precompiled_regex: function(data, cb) {
cb(data.toString('hex').toUpperCase().replace(re, "%$1"));
},
with_no_percents: function(data, cb) {
cb(data.toString('hex'));
},
};
fs.readFile('testfile.mp3', function(err, data) {
console.log('Testing urlification of binary data of ' + data.length + ' bytes')
var method_names = Object.keys(methods);
var do_next = function() {
var method = method_names.shift();
var before = new Date();
methods[method](data, function(encoded) {
var after = new Date();
var delta = after - before;
console.log(method + ': ' + (delta / 1000) + ' seconds');
if (method_names.length) do_next();
});
};
do_next();
});
/* Results:
count@bumba:~$ ./url-my-url.js
Testing urlification of binary data of 6255970 bytes
with_escape: 0.277 seconds
with_loop: 1.704 seconds
626 rescheds
with_broken_loop: 1.684 seconds
with_regex: 2.66 seconds
with_regex_lower: 2.889 seconds
with_precompiled_regex: 4.506 seconds
with_no_percents: 1.645 seconds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment