Skip to content

Commit 51587b2

Browse files
alemuresjasnell
authored andcommitted
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: #11733 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Brian White <mscdex@mscdex.net>
1 parent ebeee85 commit 51587b2

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Diff for: lib/buffer.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -836,8 +836,8 @@ Buffer.prototype.write = function(string, offset, length, encoding) {
836836

837837

838838
Buffer.prototype.toJSON = function() {
839-
if (this.length) {
840-
const data = [];
839+
if (this.length > 0) {
840+
const data = new Array(this.length);
841841
for (var i = 0; i < this.length; ++i)
842842
data[i] = this[i];
843843
return { type: 'Buffer', data };

0 commit comments

Comments
 (0)