Skip to content

Commit d7b1552

Browse files
authored
Optimize _encode_multipart_message (#75)
* Optimize _encode_multipart_message By using BytesIO while generating the body instead of continuous string concatenations. This drastically reduces execution time by not recreating the string for each concatenation. In one case, execution time fell from 140 seconds to 0.14; three orders of magnitude! * Fix comment about default chunk_size in MB
1 parent a59af6e commit d7b1552

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

src/dicomweb_client/web.py

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ def __init__(
233233
Maximum number of bytes that should be transferred per data chunk
234234
when streaming data from the server using chunked transfer encoding
235235
(used by ``iter_*()`` methods as well as the ``store_instances()``
236-
method); defaults to ``10**6`` bytes (10MB)
236+
method); defaults to ``10**6`` bytes (1MB)
237237
238238
Warning
239239
-------
@@ -743,13 +743,15 @@ def _encode_multipart_message(
743743
raise ValueError(
744744
'No "boundary" parameter in found in content-type field'
745745
)
746-
body = b''
747-
for part in content:
748-
body += f'\r\n--{boundary}'.encode('utf-8')
749-
body += f'\r\nContent-Type: {content_type}\r\n\r\n'.encode('utf-8')
750-
body += part
751-
body += f'\r\n--{boundary}--'.encode('utf-8')
752-
return body
746+
with BytesIO() as b:
747+
for part in content:
748+
b.write(f'\r\n--{boundary}'.encode('utf-8'))
749+
b.write(
750+
f'\r\nContent-Type: {content_type}\r\n\r\n'.encode('utf-8')
751+
)
752+
b.write(part)
753+
b.write(f'\r\n--{boundary}--'.encode('utf-8'))
754+
return b.getvalue()
753755

754756
@classmethod
755757
def _assert_media_type_is_valid(cls, media_type: str):

0 commit comments

Comments
 (0)