Skip to content

Commit a82003b

Browse files
mertcanaltinaduh95
authored andcommitted
buffer: optimize buffer.concat performance
PR-URL: #61721 Reviewed-By: René <contact.9a5d6388@renegade334.me.uk> Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
1 parent 2ea0672 commit a82003b

2 files changed

Lines changed: 50 additions & 9 deletions

File tree

lib/buffer.js

Lines changed: 40 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ const {
5151
TypedArrayPrototypeGetLength,
5252
TypedArrayPrototypeSet,
5353
TypedArrayPrototypeSlice,
54+
TypedArrayPrototypeSubarray,
5455
Uint8Array,
5556
Uint8ArrayPrototype,
5657
} = primordials;
@@ -626,25 +627,55 @@ Buffer.concat = function concat(list, length) {
626627
if (length === undefined) {
627628
length = 0;
628629
for (let i = 0; i < list.length; i++) {
629-
if (list[i].length) {
630-
length += list[i].length;
630+
const buf = list[i];
631+
if (!isUint8Array(buf)) {
632+
// TODO(BridgeAR): This should not be of type ERR_INVALID_ARG_TYPE.
633+
// Instead, find the proper error code for this.
634+
throw new ERR_INVALID_ARG_TYPE(
635+
`list[${i}]`, ['Buffer', 'Uint8Array'], buf);
631636
}
637+
length += TypedArrayPrototypeGetByteLength(buf);
632638
}
633-
} else {
634-
validateOffset(length, 'length');
639+
640+
const buffer = allocate(length);
641+
let pos = 0;
642+
for (let i = 0; i < list.length; i++) {
643+
const buf = list[i];
644+
const bufLength = TypedArrayPrototypeGetByteLength(buf);
645+
TypedArrayPrototypeSet(buffer, buf, pos);
646+
pos += bufLength;
647+
}
648+
649+
if (pos < length) {
650+
TypedArrayPrototypeFill(buffer, 0, pos, length);
651+
}
652+
return buffer;
635653
}
636654

637-
const buffer = Buffer.allocUnsafe(length);
638-
let pos = 0;
655+
validateOffset(length, 'length');
639656
for (let i = 0; i < list.length; i++) {
640-
const buf = list[i];
641-
if (!isUint8Array(buf)) {
657+
if (!isUint8Array(list[i])) {
642658
// TODO(BridgeAR): This should not be of type ERR_INVALID_ARG_TYPE.
643