Created
March 15, 2015 06:44
-
-
Save jrgm/a9949b6468ae1325088e to your computer and use it in GitHub Desktop.
compare json serialization: default toJSON vs. asking for an additional .toString('hex') format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Benchmark = require('benchmark'); | |
var suite = new Benchmark.Suite; | |
var obj1 = { food: Buffer('c0ffee', 'hex'), bar: 3 }; | |
var obj2 = { | |
'id': Buffer('eceb3ae8aee125e2', 'hex'), | |
'secret': Buffer('281a885146ee216844d1ffd0d725ee714101548a1e6507f1a40fb2c2ae0c11f1', 'hex'), | |
'name':'blah', | |
'imageUri':'https://blah.example.com/img/[email protected]', | |
'redirectUri':'https://blah.example.com/api/oauth', | |
'whitelisted':true, | |
'canGrant':false, | |
'createdAt': Date.now() | |
} | |
function json(obj) { | |
var seen = []; | |
return JSON.stringify(obj, function filter(key, val) { | |
if (typeof val === 'object' && val != null) { | |
if (seen.indexOf(val) !== -1) { | |
return '[Circular]'; | |
} | |
seen.push(val); | |
} | |
return val; | |
}, 0); | |
} | |
function json2(obj) { | |
var seen = []; | |
return JSON.stringify(obj, function filter(key, val) { | |
if (Buffer.isBuffer(this[key])) { | |
// `val` in this case is the toJSON result on Buffer, an array of 8-bit | |
// integers. Instead, the hex format is more compact and just as useful. | |
// A string value would not match the object check below, so return now. | |
return this[key].toString('hex') | |
} | |
if (typeof val === 'object' && val != null) { | |
if (seen.indexOf(val) !== -1) { | |
return '[Circular]'; | |
} | |
seen.push(val); | |
} | |
return val; | |
}, 0); | |
} | |
suite | |
.add('accept default toJSON() of buffer; simple object ', function() { | |
var str = json(obj1) | |
}) | |
.add('convert again with toString("hex"); simple object ', function() { | |
var str = json(obj1) | |
}) | |
.add('accept default toJSON() of buffer; more realistic object ', function() { | |
var str = json(obj2) | |
}) | |
.add('convert again with toString("hex"); more realistic object', function() { | |
var str = json(obj2) | |
}) | |
.on('cycle', function(event) { | |
console.log(String(event.target)); | |
}) | |
.on('complete', function() { | |
console.log('Fastest is ' + this.filter('fastest').pluck('name')); | |
}) | |
.run({ | |
'async': true | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment