summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--benchmark/buffers/buffer-tojson.js18
-rw-r--r--lib/buffer.js12
2 files changed, 26 insertions, 4 deletions
diff --git a/benchmark/buffers/buffer-tojson.js b/benchmark/buffers/buffer-tojson.js
new file mode 100644
index 0000000000..1be59952c3
--- /dev/null
+++ b/benchmark/buffers/buffer-tojson.js
@@ -0,0 +1,18 @@
+'use strict';
+
+const common = require('../common.js');
+
+const bench = common.createBenchmark(main, {
+ n: [1e4],
+ len: [0, 10, 256, 4 * 1024]
+});
+
+function main(conf) {
+ var n = +conf.n;
+ var buf = Buffer.allocUnsafe(+conf.len);
+
+ bench.start();
+ for (var i = 0; i < n; ++i)
+ buf.toJSON();
+ bench.end(n);
+}
diff --git a/lib/buffer.js b/lib/buffer.js
index 875dc13ac3..cae036845f 100644
--- a/lib/buffer.js
+++ b/lib/buffer.js
@@ -804,10 +804,14 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
Buffer.prototype.toJSON = function() {
- return {
- type: 'Buffer',
- data: Array.prototype.slice.call(this, 0)
- };
+ if (this.length) {
+ const data = [];
+ for (var i = 0; i < this.length; ++i)
+ data[i] = this[i];
+ return { type: 'Buffer', data };
+ } else {
+ return { type: 'Buffer', data: [] };
+ }
};