From 138d004ac0944fc1f2870e6d5024c95fda2b3878 Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Thu, 17 Dec 2015 17:44:34 +0800 Subject: [PATCH] buffer: faster case for create Buffer from new Buffer(0) When create Buffer from a Buffer will copy data from old to new even though length is zero. This patch can improve edge case 4x faster. following is benchmark results. new: buffers/buffer_zero.js n=1024: 2463.53891 old: buffers/buffer_zero.js n=1024: 618.70801 PR-URL: https://github.com/nodejs/node/pull/4326 Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- benchmark/buffers/buffer_zero.js | 18 ++++++++++++++++++ lib/buffer.js | 4 ++++ 2 files changed, 22 insertions(+) create mode 100644 benchmark/buffers/buffer_zero.js diff --git a/benchmark/buffers/buffer_zero.js b/benchmark/buffers/buffer_zero.js new file mode 100644 index 00000000000000..461378758b5951 --- /dev/null +++ b/benchmark/buffers/buffer_zero.js @@ -0,0 +1,18 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [1024] +}); + +const zero = new Buffer(0); + +function main(conf) { + var n = +conf.n; + bench.start(); + for (let i = 0; i < n * 1024; i++) { + new Buffer(zero); + } + bench.end(n); +} diff --git a/lib/buffer.js b/lib/buffer.js index 378dde79a1c085..31deb522ba190a 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -123,6 +123,10 @@ function fromString(string, encoding) { function fromObject(obj) { if (obj instanceof Buffer) { var b = allocate(obj.length); + + if (b.length === 0) + return b; + obj.copy(b, 0, 0, obj.length); return b; }