Skip to content

Commit

Permalink
fix: optimize stream sink for small messages (libp2p#216)
Browse files Browse the repository at this point in the history
Related to libp2p#1342
Shaves ~100ms when sending small chunks but we are still not close to 0.36 speed
  • Loading branch information
mpetrunic committed Sep 20, 2022
1 parent cf94f56 commit a10205b
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,17 +174,21 @@ export function createStream (options: Options): MplexStream {
const uint8ArrayList = new Uint8ArrayList()

for await (const data of source) {
uint8ArrayList.append(data)

while (uint8ArrayList.length !== 0) {
if (uint8ArrayList.length <= maxMsgSize) {
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() })
uint8ArrayList.consume(uint8ArrayList.length)
break
if (data.length <= maxMsgSize) {
send({ id, type: Types.MESSAGE, data: data instanceof Uint8ArrayList ? data : new Uint8ArrayList(data) })
} else {
uint8ArrayList.append(data)

while (uint8ArrayList.length !== 0) {
// eslint-disable-next-line max-depth
if (uint8ArrayList.length <= maxMsgSize) {
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist() })
uint8ArrayList.consume(uint8ArrayList.length)
break
}
send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) })
uint8ArrayList.consume(maxMsgSize)
}

send({ id, type: Types.MESSAGE, data: uint8ArrayList.sublist(0, maxMsgSize) })
uint8ArrayList.consume(maxMsgSize)
}
}
} catch (err: any) {
Expand Down

0 comments on commit a10205b

Please sign in to comment.