Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add decode benchmarks, improve decode performance #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions benchmarks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,22 @@ strmsg.push('baz')
// buffer

var bin = msg.toBuffer();
var bufbin = bufmsg.toBuffer();
var strbin = strmsg.toBuffer();

suite('Message', function(){
bench('decode', function(){
new Message(bin);
})

bench('decode strings', function(){
new Message(strbin);
})

bench('decode buffers', function(){
new Message(bufbin);
})

bench('encode', function(){
msg.toBuffer();
})
Expand Down
74 changes: 27 additions & 47 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,33 @@ Message.prototype.toBuffer = function(){
*/

function decode(msg) {
var args = amp.decode(msg);

for (var i = 0; i < args.length; i++) {
args[i] = unpack(args[i]);
// unpack meta
var meta = msg[0];
var version = meta >> 4;
var argv = meta & 0xf;
var args = new Array(argv);

var off = 1;

// unpack args
for (var i = 0; i < argv; i++) {
var len = msg.readUInt32BE(off) - 2;
off += 6;

// json
if (msg[off - 2] === 106 && msg[off - 1] === 58) {
args[i] = JSON.parse(msg.toString(null, off, off += len));
continue;
}

// string
if (msg[off - 2] === 115 && msg[off - 1] === 58) {
args[i] = msg.toString(null, off, off += len);
continue;
}

// blob
args[i] = msg.slice(off, off += len);
}

return args;
Expand Down Expand Up @@ -125,46 +148,3 @@ function pack(arg) {
// json
return new Buffer('j:' + JSON.stringify(arg));
}

/**
* Unpack `arg`.
*
* @param {Buffer} arg
* @return {Mixed}
* @api private
*/

function unpack(arg) {
// json
if (isJSON(arg)) return JSON.parse(arg.slice(2));

// string
if (isString(arg)) return arg.slice(2).toString();

// blob
return arg;
}

/**
* String argument.
*/

function isString(arg) {
return 115 == arg[0] && 58 == arg[1];
}

/**
* JSON argument.
*/

function isJSON(arg) {
return 106 == arg[0] && 58 == arg[1];
}

/**
* ID argument.
*/

function isId(arg) {
return 105 == arg[0] && 58 == arg[1];
}