Skip to content

Instantly share code, notes, and snippets.

Created April 4, 2013 07:13
Show Gist options
  • Select an option

  • Save anonymous/5308457 to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/5308457 to your computer and use it in GitHub Desktop.
Binary-to-url benchmark in node.js
#!/usr/bin/env node
var fs = require('fs');
var re = /(..)/g;
var methods = {
with_escape: function(data) {
return escape(data.toString('binary'));
},
with_loop: function (data) {
var buf = '';
for (var n = 0; n < data.length; n++) {
buf += '%' + data[n].toString(16);
}
return buf;
},
with_regex: function(data) {
return data.toString('hex').toUpperCase().replace(/(..)/g, "%$1");
},
with_regex_lower: function(data) {
return data.toString('hex').replace(/(..)/g, "%$1");
},
with_precompiled_regex: function(data) {
return data.toString('hex').toUpperCase().replace(re, "%$1");
},
with_no_percents: function(data) {
return data.toString('hex');
},
};
fs.readFile('testfile.mp3', function(err, data) {
console.log('Testing urlification of binary data of ' + data.length + ' bytes')
Object.keys(methods).forEach(function(method) {
var before = new Date();
var encoded = methods[method](data);
var after = new Date();
var delta = after - before;
console.log(method + ': ' + (delta / 1000) + ' seconds');
});
});
/* Results:
count@bumba:~$ ./url-my-url.js
Testing urlification of binary data of 6255970 bytes
with_escape: 0.27 seconds
with_loop: 1.643 seconds
with_regex: 2.404 seconds
with_regex_lower: 2.36 seconds
with_precompiled_regex: 2.233 seconds
with_no_percents: 1.375 seconds
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment