Skip to content

Commit f7879d9

Browse files
mscdexMylesBorins
authored andcommitted
buffer: improve toJSON() performance
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]>
1 parent 9e6fcbb commit f7879d9

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

benchmark/buffers/buffer-tojson.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'use strict';
2+
3+
const common = require('../common.js');
4+
5+
const bench = common.createBenchmark(main, {
6+
n: [1e4],
7+
len: [0, 10, 256, 4 * 1024]
8+
});
9+
10+
function main(conf) {
11+
var n = +conf.n;
12+
var buf = Buffer.allocUnsafe(+conf.len);
13+
14+
bench.start();
15+
for (var i = 0; i < n; ++i)
16+
buf.toJSON();
17+
bench.end(n);
18+
}

lib/buffer.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -785,10 +785,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
785785

786786

787787
Buffer.prototype.toJSON = function() {
788-
return {
789-
type: 'Buffer',
790-
data: Array.prototype.slice.call(this, 0)
791-
};
788+
if (this.length) {
789+
const data = [];
790+
for (var i = 0; i < this.length; ++i)
791+
data[i] = this[i];
792+
return { type: 'Buffer', data };
793+
} else {
794+
return { type: 'Buffer', data: [] };
795+
}
792796
};
793797

794798

0 commit comments

Comments
 (0)