Use bytearray()
from time import time
c = b'\x02\x03\x05\x07' * 500 # test data
# Method-1 with bytes-string
bytes_string = b''
st = time()
for _ in range(10**4):
bytes_string += c
print("string concat -> took {} sec".format(time()-st))
# Method-2 with bytes-array
bytes_arr = bytearray()
st = time()
for _ in range(10**4):
bytes_arr.extend(c)
# convert byte_arr to bytes_string via
bytes_string = bytes(bytes_arr)
print("bytearray extend/concat -> took {} sec".format(time()-st))
benchmark in my Win10|Corei7-7th Gen shows:
string concat -> took 67.27699875831604 sec
bytearray extend/concat -> took 0.08975911140441895 sec
the code is pretty self-explanatory. instead of using string+=next_block
, use bytearray.extend(next_block)
. After building bytearray
you can use bytes(bytearray)
to get the bytes-string.