How to speed up string concatenation in Python?

There is a bottleneck in the concatenation below. As you can see, I tried some complicated methods to speed it up, but its bloody slowdowns anyway. I would like to know if there is anything that I can do to make it fast.

By the way, both simple and secret are data read from a binary file, and they are quite large (about 1 mb)

x = b''
if len(plain) < len(secret*8):
    return False
i = 0

for secByte in secret:
    for j in range(8):
        z = setBit(plain[i],0,getBit(secByte,j))
        #x += bytes([z])
        x = x.join([b"", bytes([z])])
        #x = array.array("B",(int(z) for z in x.join([b"", bytes([z])]))).tostring()
        i = i+1
+3
source share
2 answers

, . bytearray , . O (N), , bytearray, , :

x = bytearray(len(secret)*8)   # creates an array of zero bytes
i = 0
for secByte in secret:
    for j in range(8):
        x[i] = setBit(plain[i], 0, getBit(secByte, j))
        i += 1
+5

Python O (1) append, , . , , . O (N ^ 2) O (N). , , setBit() getBit(), - :

L = []
for secByte in secret:
    for j in range(8):
         z = ...
         L.append(z)
x = b"".join(L)
+7

Source: https://habr.com/ru/post/1777143/


All Articles