Skip to content

Commit a437f73

Browse files
committed
buffer: improve toJSON() performance
1 parent c4b4611 commit a437f73

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

805805

806806
Buffer.prototype.toJSON = function() {
807-
return {
808-
type: 'Buffer',
809-
data: Array.prototype.slice.call(this, 0)
810-
};
807+
if (this.length) {
808+
const data = [];
809+
for (var i = 0; i < this.length; ++i)
810+
data[i] = this[i];
811+
return { type: 'Buffer', data };
812+
} else {
813+
return { type: 'Buffer', data: [] };
814+
}
811815
};
812816

813817

0 commit comments

Comments
 (0)