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.
On my computer, the following
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
buffer2is shorter thanbuffer1, and you want to copy its contents at a particular position inbuffer1without changing the rest of the target buffer, you can use the following:Similarly, you can use slicing on the right-hand side to only copy a portion of
buffer2.