From f7879d98f839ea867a2cb938beeb6a071294ebbe 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 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 84a97ea325580a..28534bab2783ad 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -785,10 +785,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: [] }; + } };