Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit a114f63

Browse filesBrowse files
mscdexItalo A. Casas
authored andcommitted
buffer: improve toJSON() performance
PR-URL: #10895 Reviewed-By: Luigi Pinca <luigipinca@gmail.com> Reviewed-By: Michal Zasso <targos@protonmail.com> Reviewed-By: Evan Lucas <evanlucas@me.com> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent 5fd0f9a commit a114f63
Copy full SHA for a114f63

File tree

Expand file treeCollapse file tree

2 files changed

+26
-4
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

2 files changed

+26
-4
lines changed
Open diff view settings
Collapse file

‎benchmark/buffers/buffer-tojson.js‎

Copy file name to clipboard
+18Lines 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+
}
Collapse file

‎lib/buffer.js‎

Copy file name to clipboardExpand all lines: lib/buffer.js
+8-4Lines changed: 8 additions & 4 deletions
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 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.