Skip to content

Commit 22c25de

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 b3a8e95 commit 22c25de

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
@@ -677,10 +677,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
677677

678678

679679
Buffer.prototype.toJSON = function() {
680-
return {
681-
type: 'Buffer',
682-
data: Array.prototype.slice.call(this, 0)
683-
};
680+
if (this.length) {
681+
const data = [];
682+
for (var i = 0; i < this.length; ++i)
683+
data[i] = this[i];
684+
return { type: 'Buffer', data };
685+
} else {
686+
return { type: 'Buffer', data: [] };
687+
}
684688
};
685689

686690

0 commit comments

Comments
 (0)