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 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.

2

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.

6

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like