Skip to content
This repository was archived by the owner on Jul 21, 2023. It is now read-only.

Commit a10205b

Browse files
authored
fix: optimize stream sink for small messages (#216)
Related to libp2p/js-libp2p#1342 Shaves ~100ms when sending small chunks but we are still not close to 0.36 speed
1 parent cf94f56 commit a10205b

File tree

1 file changed

+14
-10
lines changed

1 file changed

+14
-10
lines changed

src/stream.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -174,17 +174,21 @@ export function createStream (options: Options): MplexStream {
174174
const uint8ArrayList = new Uint8ArrayList()
175175

176176
for await (const data of source) {
177-
uint8ArrayList.append(data)
178-
179-
while (uint8ArrayList.length !== 0) {
180-
if (uint8ArrayList.length <= maxMsgSize) {
181-
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() })
182-
uint8ArrayList.consume(uint8ArrayList.length)
183-
break
177+
if (data.length <= maxMsgSize) {
178+
send({ id, type: Types.MESSAGE, data: data instanceof Uint8ArrayList ? data : new Uint8ArrayList(data) })
179+
} else {
180+
uint8ArrayList.append(data)
181+
182+
while (uint8ArrayList.length !== 0) {
183+
// eslint-disable-next-line max-depth
184+
if (uint8ArrayList.length <= maxMsgSize) {
185+
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() })
186+
uint8ArrayList.consume(uint8ArrayList.length)
187+
break
188+
}
189+
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) })
190+
uint8ArrayList.consume(maxMsgSize)
184191
}
185-
186-
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) })
187-
uint8ArrayList.consume(maxMsgSize)
188192
}
189193
}
190194
} catch (err: any) {

0 commit comments

Comments
 (0)