From de8f36dd3e55b35868f4171bf956bb179216657b Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 18 Dec 2015 10:57:21 +0800 Subject: [PATCH] buffer: faster case for create buffer from empty string When create Buffer from empty string will touch C++ binding also. This patch can improve edge case ~70% faster. --- benchmark/buffers/buffer_zero.js | 15 ++++++++++----- lib/buffer.js | 4 ++++ 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/benchmark/buffers/buffer_zero.js b/benchmark/buffers/buffer_zero.js index 4a63695657be1f..e624bbbcd43283 100644 --- a/benchmark/buffers/buffer_zero.js +++ b/benchmark/buffers/buffer_zero.js @@ -3,16 +3,21 @@ const common = require('../common.js'); const bench = common.createBenchmark(main, { - n: [1024] + n: [1024], + type: ['buffer', 'string'] }); -const zero = Buffer.alloc(0); +const zeroBuffer = Buffer.alloc(0); +const zeroString = ''; function main(conf) { var n = +conf.n; bench.start(); - for (let i = 0; i < n * 1024; i++) { - Buffer.from(zero); - } + + if (conf.type === 'buffer') + for (let i = 0; i < n * 1024; i++) Buffer.from(zeroBuffer); + else if (conf.type === 'string') + for (let i = 0; i < n * 1024; i++) Buffer.from(zeroString); + bench.end(n); } diff --git a/lib/buffer.js b/lib/buffer.js index 01a8f303e1b92c..c1c65735a1014f 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -170,6 +170,10 @@ function fromString(string, encoding) { throw new TypeError('"encoding" must be a valid string encoding'); var length = byteLength(string, encoding); + + if (length === 0) + return Buffer.alloc(0); + if (length >= (Buffer.poolSize >>> 1)) return binding.createFromString(string, encoding);