Skip to content

Commit e10034f

Browse files
committed
buffer: speed up concat via TypedArray#set
1 parent 2bda7cb commit e10034f

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

lib/buffer.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ const {
5151
TypedArrayPrototypeGetLength,
5252
TypedArrayPrototypeSet,
5353
TypedArrayPrototypeSlice,
54+
TypedArrayPrototypeSubarray,
5455
Uint8Array,
5556
} = primordials;
5657

@@ -600,7 +601,21 @@ Buffer.concat = function concat(list, length) {
600601
throw new ERR_INVALID_ARG_TYPE(
601602
`list[${i}]`, ['Buffer', 'Uint8Array'], list[i]);
602603
}
603-
pos += _copyActual(buf, buffer, pos, 0, buf.length);
604+
605+
if (buf.length === 0 || pos >= length) {
606+
// Empty buf or destination is full; subsequent copies are no-ops.
607+
// We don't break to preserve compatibility and throw if isUint8Array fails.
608+
continue;
609+
}
610+
611+
const available = length - pos;
612+
const toCopy = buf.length > available ? available : buf.length;
613+
if (toCopy === buf.length) {
614+
TypedArrayPrototypeSet(buffer, buf, pos);
615+
} else {
616+
TypedArrayPrototypeSet(buffer, TypedArrayPrototypeSubarray(buf, 0, toCopy), pos);
617+
}
618+
pos += toCopy;
604619
}
605620

606621
// Note: `length` is always equal to `buffer.length` at this point

0 commit comments

Comments
 (0)