Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a114f63

Browse files
mscdexitaloacasas
authored andcommittedJan 30, 2017
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 5fd0f9a commit a114f63

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed
 

‎benchmark/buffers/buffer-tojson.js

+18
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

+8-4
Original file line numberDiff line numberDiff line change
@@ -793,10 +793,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
793793

794794

795795
Buffer.prototype.toJSON = function() {
796-
return {
797-
type: 'Buffer',
798-
data: Array.prototype.slice.call(this, 0)
799-
};
796+
if (this.length) {
797+
const data = [];
798+
for (var i = 0; i < this.length; ++i)
799+
data[i] = this[i];
800+
return { type: 'Buffer', data };
801+
} else {
802+
return { type: 'Buffer', data: [] };
803+
}
800804
};
801805

802806

0 commit comments

Comments
 (0)
Please sign in to comment.