Skip to content

Commit

Permalink
buffer: use FastBuffer when fill is set to 0
Browse files Browse the repository at this point in the history
A large number of libraries seem to use Buffer.alloc(size, 0)
instead of just Buffer.alloc(size).

We don't need to follow the "create unsafe buffer and fill it" path
(i.e. actually allocate and perform fill) in that situation, that is
better handled by Uint8Array constructor.

Buffer.alloc(size) and Buffer.alloc(size, 0) are equivalent, so
use the same code path.

Not performing the zero-fill manually and having the underlying memory
allocator do it for us can improve speed and reduce the memory usage
for situations where Buffer.alloc(size, 0) is used.

PR-URL: #21989
Reviewed-By: Anna Henningsen <[email protected]>
Reviewed-By: Ruben Bridgewater <[email protected]>
Reviewed-By: Trivikram Kamat <[email protected]>
Reviewed-By: Minwoo Jung <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Tiancheng "Timothy" Gu <[email protected]>
Reviewed-By: Gireesh Punathil <[email protected]>
Reviewed-By: Tobias Nießen <[email protected]>
  • Loading branch information
ChALkeR authored and targos committed Aug 6, 2018
1 parent 0ca831a commit 6622ac7
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion lib/buffer.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ function assertSize(size) {
*/
Buffer.alloc = function alloc(size, fill, encoding) {
assertSize(size);
if (fill !== undefined && size > 0) {
if (fill !== undefined && fill !== 0 && size > 0) {
return _fill(createUnsafeBuffer(size), fill, encoding);
}
return new FastBuffer(size);
Expand Down

0 comments on commit 6622ac7

Please sign in to comment.