Skip to content

Commit 89be008

Browse files
committed
Optimize multipart message decoding
Avoid repeated truncation/reallocation of a bytes array, and expensive call to split()
1 parent 39dc8a7 commit 89be008

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/dicomweb_client/web.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -673,7 +673,7 @@ def _decode_multipart_message(
673673

674674
marker = b''.join((b'--', boundary))
675675
delimiter = b''.join((b'\r\n', marker))
676-
data = b''
676+
data = bytearray()
677677
j = 0
678678
with response:
679679
logger.debug('decode message content')
@@ -685,16 +685,23 @@ def _decode_multipart_message(
685685
if stream:
686686
logger.debug(f'decode message content chunk #{i}')
687687
data += chunk
688-
while delimiter in data:
688+
689+
prev_part_index = 0
690+
while (
691+
delimiter_index := data.find(delimiter, prev_part_index)
692+
) >= 0:
689693
logger.debug(f'decode message part #{j}')
690-
part, data = data.split(delimiter, maxsplit=1)
691-
content = self._extract_part_content(part)
694+
content = self._extract_part_content(
695+
data[prev_part_index:delimiter_index]
696+
)
697+
prev_part_index = delimiter_index + len(delimiter)
692698
j += 1
693699
if content is not None:
694700
logger.debug(
695701
f'extracted {len(content)} bytes from part #{j}'
696702
)
697703
yield content
704+
data = data[prev_part_index:]
698705

699706
content = self._extract_part_content(data)
700707
if content is not None:

0 commit comments

Comments
 (0)