Skip to content

Commit

Permalink
buffer: improve toJSON() performance
Browse files Browse the repository at this point in the history
PR-URL: #10895
Reviewed-By: Luigi Pinca <[email protected]>
Reviewed-By: Michal Zasso <[email protected]>
Reviewed-By: Evan Lucas <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: James M Snell <[email protected]>
  • Loading branch information
mscdex authored and italoacasas committed Jan 30, 2017
1 parent 5fd0f9a commit a114f63
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
18 changes: 18 additions & 0 deletions benchmark/buffers/buffer-tojson.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const common = require('../common.js');

const bench = common.createBenchmark(main, {
n: [1e4],
len: [0, 10, 256, 4 * 1024]
});

function main(conf) {
var n = +conf.n;
var buf = Buffer.allocUnsafe(+conf.len);

bench.start();
for (var i = 0; i < n; ++i)
buf.toJSON();
bench.end(n);
}
12 changes: 8 additions & 4 deletions lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -793,10 +793,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {


Buffer.prototype.toJSON = function() {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this, 0)
};
if (this.length) {
const data = [];
for (var i = 0; i < this.length; ++i)
data[i] = this[i];
return { type: 'Buffer', data };
} else {
return { type: 'Buffer', data: [] };
}
};


Expand Down

0 comments on commit a114f63

Please sign in to comment.