How to Copy a Python Bytearray Buffer?
I Have Two Network Buffers Defined as: Buffer1 = Bytearray(4096) Buffer2 = Bytearray(4096) Which Is the Fastest Way to Move the Content from Buffer2 to Buffer1...
I have two network buffers defined as:
buffer1 = bytearray(4096)
buffer2 = bytearray(4096)
Which is the fastest way to move the content from buffer2 to buffer1 without allocating extra memory?
The naive way would be to do:
for i in xrange(4096):
buffer1[i] = buffer2[i]
Apparently if I do buffer1[:]=buffer2[:] python moves the content, but I'm not 100% sure of it because if I do:
a = bytearray([0,0,0])
b = bytearray([1,1])
a[:]=b[:]
then len(a)=2. What happens with the missing byte? Can anyone explain how this works or how to move data between buffers?
Thanks.
1 Answer
On my computer, the following
buffer1[:] = buffer2
copies a 4KB buffer in under 400 nanoseconds. In other words, you can do 2.5 million such copies per second.
Is this fast enough for your needs?
edit: If buffer2 is shorter than buffer1, and you want to copy its contents at a particular position in buffer1 without changing the rest of the target buffer, you can use the following:
buffer1[pos:pos+len(buffer2)] = buffer2
Similarly, you can use slicing on the right-hand side to only copy a portion of buffer2.