From a437f7348d259a03647e8d3daa4f9c274c165ac0 Mon Sep 17 00:00:00 2001 From: Brian White Date: Thu, 19 Jan 2017 02:55:21 -0500 Subject: [PATCH] buffer: improve toJSON() performance --- benchmark/buffers/buffer-tojson.js | 18 ++++++++++++++++++ lib/buffer.js | 12 ++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) create mode 100644 benchmark/buffers/buffer-tojson.js diff --git a/benchmark/buffers/buffer-tojson.js b/benchmark/buffers/buffer-tojson.js new file mode 100644 index 00000000000000..1be59952c3fe60 --- /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 875dc13ac3089b..cae036845fb550 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: [] }; + } };