From 9fcd842279d8aee020c0a125db80641bb107ca36 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 PR-URL: https://github.com/nodejs/node/pull/10895 Reviewed-By: Luigi Pinca Reviewed-By: Michal Zasso Reviewed-By: Evan Lucas Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- 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 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: [] }; + } };