From 6feea085876bf88c54cc28b972389dcc608a3e10 Mon Sep 17 00:00:00 2001 From: alejandro Date: Tue, 7 Mar 2017 16:25:58 +0000 Subject: [PATCH] buffer: preallocate array with buffer length Because the final array length is known, it's better to allocate its final length at initialization time to avoid future reallocations. Also add an explicit buffer length greater than 0 comparison so it's more readable, avoids the internal ToBoolean call and follows the standard Node.js API format (as it can be checked in other similar structures where 'length > 0' is preferred over 'length') PR-URL: https://github.com/nodejs/node/pull/11733 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Brian White --- lib/buffer.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/buffer.js b/lib/buffer.js index ca73549eba..f15de7d8ac 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -799,8 +799,8 @@ Buffer.prototype.write = function(string, offset, length, encoding) { Buffer.prototype.toJSON = function() { - if (this.length) { - const data = []; + if (this.length > 0) { + const data = new Array(this.length); for (var i = 0; i < this.length; ++i) data[i] = this[i]; return { type: 'Buffer', data };