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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With