Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 777
josgek Avatar asked May 17 '12 10:05

josgek


People also ask

Is Bytearray mutable in Python?

bytearray() Syntax bytearray() method returns a bytearray object (i.e. array of bytes) which is mutable (can be modified) sequence of integers in the range 0 <= x < 256 . If you want the immutable version, use the bytes() method.

What is Bytearray datatype in Python?

The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.

What is the difference between bytes and Bytearray?

The difference between bytes() and bytearray() is that bytes() returns an object that cannot be modified, and bytearray() returns an object that can be modified.


1 Answers

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.

like image 115
NPE Avatar answered Sep 28 '22 05:09

NPE