How to copy bytearray buffer in python?

I have two network buffers that are defined as:

buffer1 = bytearray(4096) buffer2 = bytearray(4096) 

What is the fastest way to move content from buffer2 to buffer1 without allocating extra memory?

Naive way:

 for i in xrange(4096): buffer1[i] = buffer2[i] 

Apparently if I do buffer1[:]=buffer2[:] , python moves the contents, but I'm not 100% sure, because if I do this:

 a = bytearray([0,0,0]) b = bytearray([1,1]) a[:]=b[:] 

then len(a)=2 . What happens with a missing byte? Can someone explain how this works or how to move data between buffers?

Thanks.

+6
source share
1 answer

On my computer the following

 buffer1[:] = buffer2 

copies a 4 KB buffer in less than 400 nanoseconds. In other words, you can make 2.5 million such copies per second.

Is it fast enough for your needs?

edit: If buffer2 shorter than buffer1 and you want to copy its contents at a specific position in buffer1 without changing the rest of the destination buffer, you can use the following:

 buffer1[pos:pos+len(buffer2)] = buffer2 

Similarly, you can use slicing on the right side to copy only part of buffer2 .

+6
source

Source: https://habr.com/ru/post/915979/


All Articles