From 44ee33f9458b32aa3f239596d527ce6114b326ca Mon Sep 17 00:00:00 2001 From: Jackson Tian Date: Fri, 18 Dec 2015 10:09:15 +0800 Subject: [PATCH] buffer: refactor create buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use createBuffer to reduce new Uint8Array() and setPrototypeOf. PR-URL: https://github.com/nodejs/node/pull/4340 Reviewed-By: Michaël Zasso Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Trevor Norris Reviewed-By: Ben Noordhuis --- lib/buffer.js | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index 31deb522ba190a..9c6b6c94162833 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -19,13 +19,17 @@ binding.setupBufferJS(Buffer.prototype, bindingObj); const flags = bindingObj.flags; const kNoZeroFill = 0; +function createBuffer(size) { + const ui8 = new Uint8Array(size); + Object.setPrototypeOf(ui8, Buffer.prototype); + return ui8; +} function createPool() { poolSize = Buffer.poolSize; if (poolSize > 0) flags[kNoZeroFill] = 1; - allocPool = new Uint8Array(poolSize); - Object.setPrototypeOf(allocPool, Buffer.prototype); + allocPool = createBuffer(poolSize); poolOffset = 0; } createPool(); @@ -67,9 +71,7 @@ function SlowBuffer(length) { length = 0; if (length > 0) flags[kNoZeroFill] = 1; - const ui8 = new Uint8Array(+length); - Object.setPrototypeOf(ui8, Buffer.prototype); - return ui8; + return createBuffer(+length); } Object.setPrototypeOf(SlowBuffer.prototype, Uint8Array.prototype); @@ -78,9 +80,7 @@ Object.setPrototypeOf(SlowBuffer, Uint8Array); function allocate(size) { if (size === 0) { - const ui8 = new Uint8Array(size); - Object.setPrototypeOf(ui8, Buffer.prototype); - return ui8; + return createBuffer(size); } if (size < (Buffer.poolSize >>> 1)) { if (size > (poolSize - poolOffset)) @@ -95,9 +95,7 @@ function allocate(size) { // being zero filled. if (size > 0) flags[kNoZeroFill] = 1; - const ui8 = new Uint8Array(size); - Object.setPrototypeOf(ui8, Buffer.prototype); - return ui8; + return createBuffer(size); } }